ASP.Net Web项目数据库连接错误

时间:2015-04-01 21:01:55

标签: c# sql asp.net sql-server webforms

我正在努力创造注册。这是web.config

<configuration>
      <connectionStrings>
        <clear/>
        <add name="connect" connectionString="Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|web.mdf; Security=True; uid=Rahman\Rahman; pwd=12345;"/>
      </connectionStrings>
        <system.web>
          <compilation debug="true" targetFramework="4.5" />
          <httpRuntime targetFramework="4.5" />
        </system.web>

        </configuration>

这里我使用sql查询将数据写入名为Users

的表中
protected void btnReg_Click(object sender, EventArgs e) {

    SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
    string q = "Insert into Users (Username, Password) Values(@username, @password)";
    SqlCommand cmd = new SqlCommand(q, cnn);
    cnn.Open();

    try {
        cmd.Parameters.AddWithValue("@username", txtUsername.Text);
        cmd.Parameters.AddWithValue("@password", txtPass.Text);
        cmd.ExecuteNonQuery();
        cnn.Close();
        textReg.Text = "Pozitive";
    }
    catch {
        textReg.Text = "Negative";
    }
}

但遗憾的是我收到了错误

“System.Data.dll中发生'System.ArgumentException'类型的异常,但未在用户代码中处理”

错误指向此行,

SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

2 个答案:

答案 0 :(得分:0)

您需要参考System.Configuration

SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.
    ConnectionStrings["connect"].ConnectionString);

答案 1 :(得分:0)

使用

// read connection string 
private string connString = Convert.ToString (System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString); 

// use the variable for a connection
SqlConnection cnn = new SqlConnection(connString );

另外,请确保在项目中添加了对System.Configuration的引用。