Get sql connection from webconfig

 Web config

 <connectionStrings>
    <add name="ConSql" connectionString="Data Source=.; Initial Catalog=yourdbName; Integrated security=SSPI;" providerName="System.Data.SqlClient" />
    <add name="ConSQLite" connectionString="Data Source=.\Mydb.db;" providerName="System.Data.SqlClient" />
  </connectionStrings>

 Class

using System;
 using System.Configuration;
 using System.Data.SqlClient;
 using System.Data.SQLite;
 
 public class Connections
    {
        public static SqlConnection GetConnection()
        {
            SqlConnection connection;
            try
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConSql"].ConnectionString);
                con.Open();
                connection = con;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return connection;
        }

        public static SQLiteConnection GetSqliteConnection()
        {
            SQLiteConnection connection;
            try
            {
                SQLiteConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["ConSQLite"].ConnectionString);
                con.Open();
                connection = con;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return connection;
        }
    }

Post a Comment

0 Comments