很长一段时间,我的代码一直在运行,但是最近遇到这个错误,Object reference not set to an instance of an object.
不知道是不是和新建数据库的使用有关。
这是我的代码:
con2.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE ProductID=@ProductID";
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET QtyInHand=@QtyInHand WHERE ProductID=@ProductID";
cmd.Parameters.Add("@QtyInHand", SqlDbType.Int).Value = existingQty - int.Parse(quantity);
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
cmd.ExecuteNonQuery();
con2.Close();
这部分的错误:int existingQty = (int)cmd.ExecuteScalar();
当我尝试使用我的其他 SqlConnection 时:con
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE ProductID=@ProductID";
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET QtyInHand=@QtyInHand WHERE ProductID=@ProductID";
cmd.Parameters.Add("@QtyInHand", SqlDbType.Int).Value = existingQty - int.Parse(quantity);
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
cmd.ExecuteNonQuery();
con.Close();
我遇到另一个错误,部分The connection was not closed. The connection's current state is open.
错误con.Open();
。我应该如何解决这个问题?