【问题标题】:C# SQL Query - ExecuteNonQuery: Connection property has not been initializedC# SQL 查询 - ExecuteNonQuery:连接属性尚未初始化
【发布时间】:2013-09-18 05:41:11
【问题描述】:

我的 Windows 应用程序中有许多代码块使用相同的结构来执行查询。在我的代码中添加了一些新内容后,由于错误,这些内容不再起作用:

“ExecuteNonQuery:连接属性尚未初始化”

代码块都是这样的:

sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;

新代码是这样做的:

//Find Open BIN
int binNumber = 0;
int binIndex = 0;
string queryString = "SELECT * FROM bin";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, scb);
DataSet binNumbers = new DataSet();
adapter.Fill(binNumbers, "bin");
for (int i = 0; i < 150; i++)
{
    binNumber++;                    
    if(binNumbers.Tables["bin"].Rows[binIndex]["serialNumber"].ToString() == "")
{
sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;
}
binIndex++;

这些的连接在类的顶部定义。

【问题讨论】:

  • 我没有看到您实际创建连接的任何地方。
  • 这怎么可能奏效?您从未创建过连接(字符串)
  • 这通常意味着你还没有实例化连接对象。我们可以看看声明吗

标签: c# sql .net sql-server executenonquery


【解决方案1】:

您需要为其分配一个SqlConnection 对象。

 cmd.Connection = connection;

其中connection 是带有您的连接字符串等的SqlConnection 对象。

另外,为了获得良好的实践,您应该将其包装在 using:

 using (SqlConnection connection = new SqlConnection("ConnectionString")) { 
     cmd.Connection = connection;
 } 

和参数化查询以防止 SQL 注入攻击。

【讨论】:

    【解决方案2】:

    在执行之前,我们需要将 sqlconnection 对象传递给 sqlcommand 对象。

    Sqlcommand 有以下构造函数构造函数:

    1. SqlCommand()
    2. SqlCommand(字符串)
    3. SqlCommand(字符串,SqlConnection)
    4. SqlCommand(字符串、SqlConnection、SqlTransaction)
    5. SqlCommand(字符串、SqlConnection、SqlTransaction、SqlCommandColumnEncryptionSetting)

    如果我们使用 1. 默认构造函数或 2. 带一个参数(查询)的参数化构造函数,那么我们需要将连接设置为

       SqlCommand.Connection = SqlConnection;
    

    下面是工作代码sn-p:

       //create a connection object
      using (SqlConnection connection = new SqlConnection(connectionString))
        {
         //create command object, and pass your string query & connection object.
         //we can call the default constructor also and later assign these values
           SqlCommand command = new SqlCommand(queryString, connection);   
        //open the connection here,
          command.Connection.Open();
        //execute the command.
          command.ExecuteNonQuery();
        }
    

    为了确保连接总是关闭,我们应该在 using 块内打开连接,以确保在代码退出块时连接自动关闭。

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 2011-07-22
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多