将字符串转换为SqlConnection时出错

Los*_*_CS -5 c# sql sql-server type-conversion

我收到这个错误:

无法将类型字符串隐式转换为System.Data.SqlClient.SqlConnection

这是我的C#代码.

protected void Button1_Click(object sender, EventArgs e)
{
  //login button
  SqlConnection sqlConn = "Your Conncetion String"; //The error is here
  sqlConn.Open();

  SqlCommand sqlComm = new SqlCommand();
  sqlComm.CommandText = String.Format("select * from users where userName=@userName and password=@password");
  sqlComm.Parameters.AddWithValue("@userName", TextBox1.Text.Trim());
  sqlComm.Parameters.AddWithValue("@password", TextBox2.Text.Trim());
  sqlComm.CommandType = CommandType.Text;
  sqlComm.Connection = sqlConn;
  SqlDataReader sqlRead = sqlComm.ExecuteReader();
  if (sqlRead.Read())
  {
    Session["username"] = sqlRead["username"];
  }

  // SqlRead.Close();

  //sqlConn1.Close();

  Response.Redirect("Default.aspx");

}
Run Code Online (Sandbox Code Playgroud)

有人可以解释这个错误意味着什么以及如何解决它?

Szy*_*mon 5

我知道你有一个连接字符串,想要一个SqlConnection对象.您可以使用其构造函数之一:

string connString = "Your Conncetion String"; // valid connection string
var sqlConn = new SqlConnection(connString);
Run Code Online (Sandbox Code Playgroud)

最好使用using关键字,因为这将正确关闭连接.你也应该用using你的SqlReader.

using (var sqlConn = new SqlConnection(connString))
{
    sqlConn.Open();
    // the rest of the code
}
Run Code Online (Sandbox Code Playgroud)