Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change connection string initial catalog

I have a connection string in web config file. I used this connection with name in all my files.

connection string is like

<add name="connectionname" connectionString="Data Source=DEVELOPER1;Initial Catalog=dbname;Persist Security Info=True;User ID=sa;Password=some"/>

I want to change initial catalog (database name) in my login page as per dropdown and that change will remain same for the application.

like image 696
Vivek Parikh Avatar asked Nov 24 '11 11:11

Vivek Parikh


1 Answers

To change the connection string without modify it, you should do the following procedure:

  1. Create a SqlConnectionStringBuilder object Assign your original connection string to it
  2. Change the parameters that you want in the created SqlConnectionStringBuilder object.
  3. Adding the SqlConnectionStringBuilder ConnectionString property to your DbConnection Object.

See the following example: (suppose that first you are created a normal DbConnection with your original conexion string (name db here)):

if (db != null)
{
    SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(db.ConnectionString)
   { ConnectTimeout = 5, InitialCatalog = "your CatalogName" }; // you can add other parameters.
      db.ConnectionString = conn.ConnectionString;
      db.Open();
      return true;
   }
}

In the given example, the Initial Catalog and the timeout were changed without touch the original string.

I hope that this help you.

like image 104
freedeveloper Avatar answered Sep 28 '22 00:09

freedeveloper