在我的项目中,我有一个需要返回ConnectionStringSettings
对象的方法。由于数据库和服务器名称将动态更改,我需要动态
构造连接字符串。
如何将string
转换为ConnectionStringSettings
?
public ConnectionStringSettings getConnection(string server, string database)
{
//ConnectionStringSettings connsettings = new ConnectionStringSettings();
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
// Need to convert connection to ConnectionStringSettings
// Return ConnectionStringSettings
}
- 的Web.config
<add name="myConnString" connectionString="server={0};Initial Catalog={1};uid=user1;pwd=blah; Connection Timeout = 1000"/>
答案 0 :(得分:1)
ConnectionStringSettings类构造函数有一个带有两个字符串的重载(第一个是连接字符串的名称,第二个是连接字符串本身)。
public ConnectionStringSettings getConnection(string server, string database)
{
string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();
connection = string.Format(connection, server, database);
return new ConnectionStringSettings("myConnString", connection);
}
有一个third overload,它为提供者的名称提供了额外的字符串。