数据库
首页 > 数据库> > C#SQL查询 – ExecuteNonQuery:尚未初始化Connection属性

C#SQL查询 – ExecuteNonQuery:尚未初始化Connection属性

作者:互联网

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

“ExecuteNonQuery: Connection property has not been initialized”

代码块看起来像这样:

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++;

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

解决方法:

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

 cmd.Connection = connection;

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

另外,对于良好的练习,您应将其包装在使用中:

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

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

标签:c,sql,net,executenonquery
来源: https://codeday.me/bug/20190629/1325424.html