动态构建连接字符串

时间:2014-05-01 11:40:35

标签: c# .net

有这些项目:

ConnDatabase
ConnServer
ConnUsername
ConnPassword

作为字符串,生成SQL服务器连接字符串的最佳方法是什么,可以在web.config文件中找到?

PS:

这实际上(很可能)是用于精致的

1 个答案:

答案 0 :(得分:4)

假设您正在构建一个SQL连接字符串,那么就有一个专门的框架类:SqlConnectionStringBuilder

以下是MSDN文章的摘录:

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);

导致此安全(引用)值:

Source=(local);Initial Catalog="AdventureWorks;NewValue=Bad";Integrated Security=True

这个类也有助于解析连接字符串,这可能非常有用(如果没有比构建它们更有用,IMO):

var builder = new SqlConnectionStringBuilder();
builder.ConnectionString = myConnectionString;
var dataSource = builder["Data Source"];