長時間以來,我的代碼一直在運行,但最近我遇到了這個錯誤,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 [email protected]";
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET [email protected] WHERE [email protected]";
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.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE [email protected]";
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
int existingQty = (int)cmd.ExecuteScalar();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE Inventory SET [email protected] WHERE [email protected]";
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();
部分。我應該如何解決這個問題?