我正在学习通过单击按钮从文本框写入数据库。我已经在我的 web.config
文件中指定了 NorthWind 数据库的连接字符串。但是我无法访问我后面的代码中的连接字符串。
这是我试过的。
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
我得到了
的工具提示错误SqlConnection sql = new SqlConnection(constring);
作为
System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.
我想从 constring
中的 web.config
加载连接字符串
最佳答案
您可以简单地在 web.config
文件中为您的 ConnectionString
提供一个 Name
并执行此操作:
网络配置:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
代码隐藏:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
关于c# - 从 web.config 文件获取 sql 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15540806/