用变量修改连接字符串 [英] Modifying connection string with variables
问题描述
所以我的目标是要有一个设置表单,允许用户编辑连接字符串(通过更改数据库名称/服务器位置。)
so my goal is to have a "settings form" which allows users to edit the connection string (by changing the database name / server location.
这是因为它可能需要在没有任何C#经验的人(前端GUI)不久之后更改服务器位置时进行更改。
The reason for this is that it it needs to be able to changed when the server locations changes shortly by someone who may not have any C# experience (Front-End GUI).
I'在app.config中创建了连接字符串,但找不到在conn字符串中分配可以更改的变量的方法?我已经使用项目属性创建了一些应用程序范围的设置,这就是我的app.config
I've created the connection strings in app.config but cannot find a way to assign variables inside the conn string that can be changed? I've created some application wide settings using the project properties. This is my app.config
<connectionStrings>
<add name="xxxx"
connectionString="Data Source=ServerIP;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=password"
providerName="System.Data.SqlClient" />
</connectionStrings>
<applicationSettings>
<xxx.Properties.Settings>
<setting name="ServerIP" serializeAs="String">
<value />
</setting>
<setting name="DBName" serializeAs="String">
<value />
</setting>
</xxx.Properties.Settings>
</applicationSettings>
推荐答案
一种实现此目的的方法是使用占位符( {0}
和 {1}
),用于配置文件中连接字符串的那些部分,如下所示:
One way to accomplish this would be to use placeholders ({0}
and {1}
) for those parts of the connection string in the config file, like so:
Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=user;Password=password
然后通过 string.Format $ c $填写c>当您在代码中读取连接字符串时,如以下示例所示。 (注意:这假定您已添加对 System.Configuration.dll 的引用,并且已将应用程序设置检索到两个变量
serverIP
和 dbName
。)
And then fill them in via string.Format
when you read the connection string in your code, as in the following example. (Note: This assumes that you've added a reference to System.Configuration.dll, and that you've retrieved the application settings into two variables, serverIP
and dbName
.)
using System.Configuration;
...
string connectionString = string.Format(
ConfigurationManager.ConnectionStrings["xxxx"].ConnectionString,
serverIP,
dbName);
这篇关于用变量修改连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!