从web获取sql连接字符串.配置文件

本文关键字:字符串 配置文件 连接 sql web 获取 | 更新日期: 2023-09-27 18:04:55

我正在学习从一个文本框中写入一个数据库,点击一个按钮。我已经在我的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)有一些无效的参数

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

从web获取sql连接字符串.配置文件

您可以简单地给web.config文件中的ConnectionString一个Name,并这样做:

网络。配置:

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

代码隐藏:

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

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

试试这个

SqlConnection sql = new SqlConnection(constring.ConnectionString);

try this

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

我建议您创建一个函数,而不是直接访问web。配置文件如下

    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='"?'"/>"));
    }

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