使用变量修改连接字符串
本文关键字:连接 字符串 修改 变量 | 更新日期: 2023-09-27 18:25:55
所以我的目标是拥有一个"设置表单",允许用户编辑连接字符串(通过更改数据库名称/服务器位置。
这样做的原因是,当可能没有任何C#经验的人(前端GUI)很快更改服务器位置时,它需要能够进行更改。
我已经在app.config中创建了连接字符串,但找不到在可以更改的conn字符串中分配变量的方法?我已经使用项目属性创建了一些应用程序范围的设置。这是我的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>
尝试SqlConnectionStringBuilder类。
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Create a new SqlConnectionStringBuilder and
// initialize it with a few name/value pairs.
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder(GetConnectionString());
// The input connection string used the
// Server key, but the new connection string uses
// the well-known Data Source key instead.
Console.WriteLine(builder.ConnectionString);
// Pass the SqlConnectionStringBuilder an existing
// connection string, and you can retrieve and
// modify any of the elements.
builder.ConnectionString = "server=(local);user id=ab;" +
"password= a!Pass113;initial catalog=AdventureWorks";
// Now that the connection string has been parsed,
// you can work with individual items.
Console.WriteLine(builder.Password);
builder.Password = "new@1Password";
builder.AsynchronousProcessing = true;
// You can refer to connection keys using strings,
// as well. When you use this technique (the default
// Item property in Visual Basic, or the indexer in C#),
// you can specify any synonym for the connection string key
// name.
builder["Server"] = ".";
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
Console.WriteLine(builder.ConnectionString);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
private static string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Server=(local);Integrated Security=SSPI;" +
"Initial Catalog=AdventureWorks";
}
}
实现这一点的一种方法是在配置文件中为连接字符串的这些部分使用占位符({0}
和{1}
),如下所示:
Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=user;Password=password
然后在读取代码中的连接字符串时,通过string.Format
填充它们,如下例所示。(注意:这假设您已经添加了对System.Configuration.dll的引用,并且您已经将应用程序设置检索到两个变量serverIP
和dbName
中。)
using System.Configuration;
...
string connectionString = string.Format(
ConfigurationManager.ConnectionStrings["xxxx"].ConnectionString,
serverIP,
dbName);