nate
nate

Reputation: 1428

Change SQL Server Database Connection Dynamically

I have a connection class that I use to connect to my database, every time I do a select, insert, etc... statement. I have the connection string hard coded in the class.

The issue with this is, if I have to change database servers, then I have to change the string on every application, and republish.

Here is my connection string:

var cnnString = string.Format("user id=sa;" +
                                          "password=pw;server=database\\instance;" +
                                          "database=dbase; " +
                                          "connection timeout=10");

I thought about creating a table and storing the database info in there, but that doesn't help if can't use the connection class to select from the database.

Is there a way of doing this dynamically?

Upvotes: 2

Views: 1996

Answers (2)

Herbey
Herbey

Reputation: 361

You can use your Appconfig file

<appSettings>    
    <add key="dbserver" value="IP_SERVER" />
    <add key="dbname" value="DB_NAME" />
    <add key="dbuser" value="sa" />
    <add key="dbpass" value="PASSWORD" />
 </appSettings>

then use this to create the string conection

string strConexion = "Data Source='" + ConfigurationManager.AppSettings["dbserver"] + "';" +
                                "Initial Catalog='" + ConfigurationManager.AppSettings["dbname"] + "';" +
                                "User Id='" + ConfigurationManager.AppSettings["dbuser"] + "';" +
                                "Password='" + ConfigurationManager.AppSettings["dbpass"] + "';";

And you can use a form to change the configuration values using this

// Open App.Config of executable

    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        config.AppSettings.Settings.Remove("dbserver");
        config.AppSettings.Settings.Remove("dbname");
        config.AppSettings.Settings.Remove("dbuser");
        config.AppSettings.Settings.Remove("dbpass");

        // Add an Application Setting.
        config.AppSettings.Settings.Add("dbserver", txtDBServer.Text);
        config.AppSettings.Settings.Add("dbname", txtDBName.Text);
        config.AppSettings.Settings.Add("dbuser", txtDBUser.Text);
        config.AppSettings.Settings.Add("dbpass", txtDBPassword.Text);

Save the changes in App.config file.

 config.Save(ConfigurationSaveMode.Modified);

Force a reload of a changed section.

ConfigurationManager.RefreshSection("appSettings");

Upvotes: 1

Riad Baghbanli
Riad Baghbanli

Reputation: 3319

Place your connection strings in .config file and use ConfigurationManager class: https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager%28v=vs.110%29.aspx

Load all you connection strings into array / Dictionary then once you need to create connection using the appropriate connection string.

Upvotes: 2

Related Questions