简体   繁体   中英

How to change connection string in app.config

I have a program that generates reports by using DataTables created by TableAdapters. Now my client has a new database, and he wants to be able to switch between the new one and the old one. I found that I can do it by changing the connection string in the app.config, but I don't know how to do it during run time. Can you suggest me a way? Thanks

I don't know how to do it during run time

Don't. You can have multiple connection strings in the app.config and access each when needed.

Configuration:

<connectionStrings>
  <add name="conn1" providerName="System.Data.SqlClient"
       connectionString="..." />
  <add name="conn2" providerName="System.Data.SqlClient"
       connectionString="..." />
</connectionStrings>

In code:

var conn1 = ConfigurationManager.ConnectionStrings["conn1"];
var conn2 = ConfigurationManager.ConnectionStrings["conn2"];

You can define more than one connection strings like this:

<add name="Conn" connectionString="Data Source=PC\SQLEXPRESS;Initial Catalog=NHIB;Integrated Security=True" providerName="System.Data.SqlClient"/>-->
<add name="Conn1" connectionString="Data Source=WINSERVER;Initial Catalog=NHIB1;Integrated Security=True;" providerName="System.Data.SqlClient"/>

And after that you can use conn or conn1 based on your requirement..like:

SqlConnection con;
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn"));  Or
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn1"));

You can switch between them as below:

string connectionString = HttpContext.Current.Request.IsLocal ? 
ConfigurationManager.ConnectionStrings["Conn"].ConnectionString :
ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
yourDataContext = new YourApplicationDataContext(connectionString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM