我的配置文件中有一个连接字符串,我在我的代码中使用它,如下所示 -
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
我需要从中获取服务器名称和数据库,并将其作为参数传递给我的存储过程。
我想尝试如下,但它失败了。
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
SqlConnectionStringBuilder conbuilder = new SqlConnectionStringBuilder();
conbuilder.ConnectionString = sqlconn.ToString();
string server = conbuilder.DataSource;
string database = conbuilder.InitialCatalog;
请帮我从配置文件中获取数据库和服务器名称
答案 0 :(得分:2)
您没有正确分配连接字符串属性,请尝试:
builder.ConnectionString = ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString;
或使用连接字符串初始化SqlConnectionStringBuilder
类,例如
var conBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["DBCentralW2"].ConnectionString);
答案 1 :(得分:0)
尝试以下:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.ConnectionString = sqlconn.ConnectionString;
string server = builder.DataSource;
string database = builder.InitialCatalog;
答案 2 :(得分:0)
我建议您将连接字符串存储在web.config中,而不是按原样存储,而不是构建它
web.config中的
<add name="connStr" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=dbtest; Integrated Security=SSPI" />
在cs文件中
string connectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();