【问题标题】:Error while converting string to SqlConnection将字符串转换为 SqlConnection 时出错
【发布时间】:2014-01-23 03:54:34
【问题描述】:

我收到此错误:

无法将类型字符串隐式转换为 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");

}

谁能解释这个错误的含义以及如何解决它?

【问题讨论】:

  • 你需要展示你的代码!
  • 有关您编写的代码问题的问题必须描述具体问题并包含有效代码以在问题本身中重现它。
  • 显示代码 (vtc)
  • 错误信息再清楚不过了。你有哪些不明白的地方?
  • 应该是SqlConnection sqlConn = new SqlConnection("Your Conncetion String")

标签: c# sql sql-server type-conversion


【解决方案1】:

我知道您有一个连接字符串并想要一个SqlConnection 对象。您可以使用它的构造函数之一:

string connString = "Your Conncetion String"; // valid connection string
var sqlConn = new SqlConnection(connString);

最好使用using 关键字,因为这将负责正确关闭连接。您还应该使用using 作为您的SqlReader

using (var sqlConn = new SqlConnection(connString))
{
    sqlConn.Open();
    // the rest of the code
}

【讨论】:

    【解决方案2】:

    改变

    SqlConnection sqlConn = "Your Conncetion String"; 
    

    收件人

    SqlConnection sqlConn = new SqlConnection("Your Conncetion String");
    

    【讨论】:

      【解决方案3】:

      应该是

      SqlConnection sqlConn = new SqlConnection("Your Conncetion String");
      

      您可以从 web.config 中读取它

      SqlConnection sqlConn = new  
      SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
      

      现在这个错误当前上下文中不存在名称“ConfigurationManager”

      1. 您必须添加对System.Configuration.dll的引用

      2. 然后将using System.Configuration; 添加到您的班级。

      3. 您现在可以像这样访问您的配置文件:

        ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

      【讨论】:

      • 初始化字符串的格式不符合从索引 0 开始的规范。
      • 现在这个错误当前上下文中不存在名称'ConfigurationManager'
      猜你喜欢
      • 2013-05-23
      • 2012-07-29
      • 2013-06-29
      • 2019-02-04
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多