C# C SQL查询-ExecuteOnQuery:尚未初始化连接属性

C# C SQL查询-ExecuteOnQuery:尚未初始化连接属性,c#,sql,.net,sql-server,executenonquery,C#,Sql,.net,Sql Server,Executenonquery,我的Windows应用程序中有许多代码块,它们使用相同的结构来执行查询。在我的代码中添加了一些新内容后,由于以下错误,这些内容不再有效: ExecuteOnQuery:尚未初始化连接属性 代码块都如下所示: sc.Open(); cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber); cmd.ExecuteNonQuery(); s

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

ExecuteOnQuery:尚未初始化连接属性

代码块都如下所示:

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++;
这些连接在类的顶部定义。

您需要为其分配一个对象

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

此外,为了获得良好的实践效果,您应该使用以下方法将其包装在一个容器中:


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

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

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

SqlCommand SqlCommandString SqlCommandString,SqlConnection SqlCommandString、SqlConnection、SqlTransaction SqlCommandString、SqlConnection、SqlTransaction、SqlCommandColumnEncryptionSetting 如果我们使用的是1。默认构造函数或2。带一个参数查询的参数化构造函数,然后我们需要将连接设置为

   SqlCommand.Connection = SqlConnection;
以下是工作代码段:

   //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块内部打开连接,以确保当代码退出块时连接自动关闭。

我看不到您实际创建连接的任何地方。这是怎么回事?您从未创建连接字符串这通常意味着您尚未安装连接对象。我们能看看申报单吗
   SqlCommand.Connection = SqlConnection;
   //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();
    }