c# - 从 web.config 文件获取 sql 连接字符串

标签 c# asp.net sql-server web-config connection-string

我正在学习通过单击按钮从文本框写入数据库。我已经在我的 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/

相关文章:

c# - 调用存储过程 SQL

c# 你如何线程递归目录搜索?

jquery - 如何从 mvc 中的单个 View 插入/更新/删除记录

sql - 确定字符串是否包含子字符串的用户定义函数

c# - 如何使用 Linq-to-SQL 删除具有空外键的行?

c# - 如何在 .NET 中获取计算机名称

c# - 从Web应用程序到桌面应用程序

c# - ASP :menu with image has padding above

ASP.NET App-设置IE7兼容模式吗?

sql-server - 多支点