出现InvalidOperationException连接没有关闭。连接的当前状态为开启 [英] InvalidOperationException The connection was not closed. The connection's current state is open
本文介绍了出现InvalidOperationException连接没有关闭。连接的当前状态为开启的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这个代码抛出一个无效操作异常
Why does this code throw an Invalid Operation Exception?
private SqlCommand cmd; // initialized in the class constructor
public void End(string spSendEventNotificationEmail) {
try {
cmd.CommandText = spSendEventNotificationEmail;
cmd.Parameters.Clear();
cmd.Parameters.Add("@packetID", SqlDbType.Int).Value = _packetID;
cmd.Parameters.Add("@statusID", SqlDbType.Int).Value = _statusID;
cmd.Parameters.Add("@website", SqlDbType.NVarChar, 100).Value = Tools.NextStep;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
} finally {
cmd.Connection.Close();
cmd.Parameters.Clear();
cmd.Dispose();
}
endCall = true;
}
推荐答案
您正试图打开这已经是打开的连接,这结果异常。
You're trying to open a connection which is already open, this results in exception.
解决方法1(推荐):
检查你的代码,检查所有其中, cmd.Connection
连接打开,并确保它总是正确关闭部分。
Inspect your code, check all the parts where cmd.Connection
connection is opened and ensure that it's always closed properly.
解决方案2( quick'n'dirty修复):
前行
cmd.Connection.Open();
添加下面的检查/清除代码:
add the following check/cleanup code:
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
这篇关于出现InvalidOperationException连接没有关闭。连接的当前状态为开启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文