![](/img/trans.png)
[英]How to solve ExecuteNonQuery: Connection property has not been initialized
[英]how to solve error of “ ExecuteNonQuery: Connection property has not been initialized?”
con = new SqlConnection (cs);
SqlCommand UpdateCommand = new SqlCommand("Update Stock Set ConfigID = @ConfigID , Quantity = @Quantity ,TotalPrice =@TotalPrice, StockDate =@StockDate ,Where StockID='" +txtStockID.Text+"'");
UpdateCommand.Parameters.Add("@ConfigID",SqlDbType.Int).Value= txtConfigID.Text;
UpdateCommand.Parameters.Add("@Quantity", SqlDbType.Int).Value = txtQty.Text;
UpdateCommand.Parameters.Add("@TotalPrice", SqlDbType.Int).Value = txtTotalPrice.Text;
UpdateCommand.Parameters.Add("@StockDate", SqlDbType.NVarChar, 50).Value = dtpStockDate.Value;
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();
我发现此错误消息是可以理解的,不是吗? 但是,必须使用构造函数或属性Connection
将连接分配给SqlCommand
:
string updateSQL = @"UPDATE Stock Set ConfigID = @ConfigID,
Quantity = @Quantity,
TotalPrice = @TotalPrice,
StockDate = @StockDate
WHERE StockID = @StockID";
SqlCommand UpdateCommand = new SqlCommand(updateSQL, con);
要么
SqlCommand UpdateCommand = new SqlCommand(updateSQL);
UpdateCommand.Connection = con;
Where
为StockID
添加了一个参数,并删除了Where
之前的最后一个逗号。 还要注意,完成后应该关闭连接,因此可以使用using
-statement来确保即使在发生错误时也可以将其释放/关闭:
using(var con = new SqlConnection (cs)) { // ... }
如何解决“ ExecuteNonQuery:连接属性尚未初始化?”的错误?
通过初始化Connection
属性
UpdateCommand.Connection = con;
UpdateCommand.ExecuteNonQuery();
另外,您还应该使用using语句包装连接对象,以确保正确处理它。
您还可以使用该连接来创建命令:
var command = connection.CreateCommand();
这样可以确保您使用正确的连接初始化了命令。 您可以使用属性command.CommandText
设置查询字符串:
command.CommandText = @"SELECT foo FROM foo";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.