C# 错误:对象引用未设置为对象的实例。/连接未关闭。连接';它的当前状态是开放的
我的代码已经运行了很长时间,但最近我遇到了这个错误,C# 错误:对象引用未设置为对象的实例。/连接未关闭。连接';它的当前状态是开放的,c#,asp.net,visual-studio-2012,C#,Asp.net,Visual Studio 2012,我的代码已经运行了很长时间,但最近我遇到了这个错误,对象引用没有设置为对象的实例。我不知道它是否与新数据库的创建和使用有关 这是我的密码: con2.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "SELECT QtyInHand FROM Inventory WHERE ProductID=@ProductID"; cmd.Parameters
对象引用没有设置为对象的实例。
我不知道它是否与新数据库的创建和使用有关
这是我的密码:
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();
我遇到另一个错误,连接未关闭。连接的当前状态为打开。
con.open()上出现错误代码>零件。如何解决此问题?对于第一个错误,您的executeScalar()
调用返回空值。要么优化查询(您可以直接在数据库中运行查询来检查查询),要么更改逻辑以处理空值
对于第二个错误,如果调用Open()
引发了该错误,那是因为连接对象以前正在使用,并且没有正确关闭。重用这样的连接通常被认为是不好的做法,所以当您打开一个连接实例时,请考虑创建一个新的连接实例。
编辑:我试图在第二段中暗示一些东西,但现在我觉得我必须明确指出:不要忘了处理您在那里留下的连接,因为它可能是您的应用程序的主要性能瓶颈。特别是因为它是ASP.NET。一旦不需要连接,就立即处理它们。当你为一个连接调用Dispose()
时,它会被关闭——同时还有其他更精细的内存管理过程。一有时间,就阅读该语句及其在连接中的用法