从web.config文件获取SQL连接字符串

12

我正在学习如何在单击按钮时从文本框向数据库写入数据。我已经在我的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);

as

System.data.SqlClient.Sqlconnection.Sqlconnection(string)有一些无效的参数。

我想从web.config中加载连接字符串到constring中。


2
这与问题无关,但从文本框编写到数据库会导致 SQL 注入。 - CodeGuru
@Popeye 是吗?你有什么建议?在数据库中存储用户输入值的更好方法是什么? - A_AR
只需在谷歌上搜索,您也可以参考此网址http://www.mikesdotnetting.com/Article/113/Preventing-SQL-Injection-in-ASP.NET。 - CodeGuru
4个回答

12
你可以在web.config文件中为你的ConnectionString简单地给出一个Name,然后这样做:

web.config:

<add name="ConnectionStringName"  connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>

代码后置:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());

8
那是因为 ConnectionStrings 集合是一个 ConnectionStringSettings 对象的集合,但 SqlConnection 构造函数需要一个 string 参数。所以你不能只单独传入 constring

请尝试使用以下方法。

SqlConnection sql = new SqlConnection(constring.ConnectionString);

4

试一下

readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());

0
我建议您创建一个函数,而不是直接访问web.config文件,如下所示
    public static string GetConfigurationValue(string pstrKey)
    {
        var configurationValue = ConfigurationManager.AppSettings[pstrKey];
        if (!string.IsNullOrWhiteSpace(configurationValue))
            return configurationValue;

        throw (new ApplicationException(
            "Configuration Tag is missing web.config. It should contain   <add key=\"" + pstrKey + "\" value=\"?\"/>"));

    }

在你的应用程序中使用这个函数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接