InvalidOperationException 连接未关闭.连接的当前状态是打开的 [英] InvalidOperationException The connection was not closed. The connection's current state is open

查看:39
本文介绍了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(快速修复):

行前

cmd.Connection.Open();

添加以下检查/清理代码:

add the following check/cleanup code:

if (cmd.Connection.State == ConnectionState.Open)
{
    cmd.Connection.Close();
}

这篇关于InvalidOperationException 连接未关闭.连接的当前状态是打开的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆