app.config文件中有多个SQL Server连接字符串

Ben*_*zar 12 c# sql-server connection-string app-config

我有兴趣在Windows窗体应用程序中显示N个单选按钮列表,供用户选择目标数据库服务器.我想在app.config文件中添加SQL Server连接字符串,因此它们在运行时由应用程序读取,并在窗体中作为单选按钮呈现.

起初我想过使用分隔符来分隔连接

  <appSettings>
    <add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

然后拆分键值对.

是否有可能以不同的方式做到这一点?

mar*_*c_s 31

要从app.config中查找所有已定义的连接字符串,请使用ConfigurationManager(来自System.Configuration).

它有一个枚举:ConfigurationManager.ConnectionStrings它包含你的所有条目<connectionStrings>.

您可以使用以下代码循环它:

foreach(ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
   string name = css.Name;
   string connString = css.ConnectionString;
   string provider = css.ProviderName;
}
Run Code Online (Sandbox Code Playgroud)

Name只是你给你的连接字符串的符号名称 - 它可以是任何东西,真的.

ConnectionString是连接字符串本身.

ProviderName是连接提供程序的名称,例如,System.Data.SqlClient用于SQL Server(以及其他数据库系统的其他用户).如果省略providerName=config中连接字符串中的属性,则默认为SQL Server(System.Data.SqlClient).


d91*_*jal 14

使用connectionStrings部分定义连接字符串.

<connectionStrings>
    <add name="connection1" connectionString="user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30"/>
    <add name="connection2" connectionString="user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)

  • foreach(ConfigurationManager.ConnectionStrings中的ConnectionStringSettings connSettings){} (2认同)