app.config 文件中的多个 SQL Server 连接字符串 [英] Multiple SQL Server connection strings in app.config file

查看:22
本文介绍了app.config 文件中的多个 SQL Server 连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.

一开始想用定界符来分隔连接

At first I thought of using a delimiter to separate the connections

  <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>

然后拆分键值对.

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

Is it possible to do this in a different way?

推荐答案

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

To find all defined connection strings from your app.config, use the ConfigurationManager (from System.Configuration).

它有一个枚举:ConfigurationManager.ConnectionStrings,其中包含您的 中的所有条目.

It has an enumeration: ConfigurationManager.ConnectionStrings which contains all entries in your <connectionStrings>.

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

You can loop over it with this code:

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

Name 只是您为连接字符串指定的符号名称 - 它可以是任何东西,真的.

The Name is just the symbolic name you give your connection string - it can be anything, really.

ConnectionString 是连接字符串本身.

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

The ProviderName is the name of the provider for the connection, e.g. System.Data.SqlClient for SQL Server (and others for other database system). If you omit the providerName= attribute from your connection string in config, it defaults to SQL Server (System.Data.SqlClient).

马克

这篇关于app.config 文件中的多个 SQL Server 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆