Dynamic Connections to variable databases in c sharp

Say we have Four different Databases and their connections as well which are stored in configuration file like web.Config or <App-Name>.config and we are in need to connect to different database depending upon user type



Connection Strings We Have:

 

<add name = "OracleConString" connectionString  = @"provider=MSDAORA;data source=ORCL;user id=SCOTT;password=TIGER" />

 

<add name = "OdbcConString" connectionString  = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\Northwind.mdb" />

 

<add name "OleDbConString" connectionstring  = @"Provider=SQLOLEDB.1;Password=pw;Persist Security Info=False" />

User ID=admin;Initial Catalog=biblio;Data Source=betav9;

Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;

Workstation ID=BETAV9;Use Encryption for Data=False;

Tag with column collation when possible=False"/>

 

<add name ="SqlServerConString" connectionString = @"data source = .\SQLEXPRESS; Integrated Security = SSPI; AttachedDBFileName = abc.mdf; User Instance = true" providerName="System.Data.SqlClient"/>

 

When we have taken a decision over user type, we may pass a value to if else structure or case.  Depending upon the value you can get the type of connection to

a database we want.


Object dbCon = null; 

 

switch(userType)

{


case "sqlConnection"

dbCon = new SqlConnection("SqlServerConString");

// provide appropriate sql command

break;

 

case "OleDbConnection"       

dbCon =  new System.Data.OleDb.OleDbConnection("OleDbConString");

// provide appropriate sql command

break;

 

case "OdbcConnection"

dbCon = new OdbcConnection("OdbcCongString");

// provide appropriate sql command

break;

 

case "OracleConnection"

dbCon = new OleDbConnection ("OracleConString");

// provide appropriate sql command

break;

}

Ebook Download
View all
Learn
View all