错误:ExecuteReader 需要一个打开且可用的连接。该连接的当前状态为打开。

13

我有一个使用MVC 4的网站,其中包含以下DataHelperClass来执行查询。我的问题是有时候网站会出现像标题那样的异常。我使用了using块来处理SqlCommand和SqlDataAdapter,但是没有成功。

请帮帮我,对我的英语表示抱歉。

        try
        {
            if (_conn.State == ConnectionState.Closed)
                _conn.Open();

            using (SqlCommand sqlCommand = new SqlCommand(query, _conn))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;

                if (parameters != null)
                    sqlCommand.Parameters.AddRange(parameters);

                //// check transaction is exist
                if (_trans != null)
                    sqlCommand.Transaction = _trans;

                DataTable dt = new DataTable();
                using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(dt);
                }

                return dt;
            }
        }
        finally
        {
            //// close connection automatically if transaction is not exist
            if (_trans == null) { _conn.Close(); }
        }

很可能你在示例中没有展示的 static SqlConnection _conn 是问题所在。 - Alexei Levenkov
1个回答

9
可能是因为您的连接没有真正打开,因为当调用此代码时:
if (_conn.State == ConnectionState.Closed)
      _conn.Open();

连接状态可能是: Broken, Connecting 或者 Fetching (查看所有的枚举列表)。

如果你试图在多个线程之间共享连接,就可能会出现这种情况。我认为每次调用该方法时,你需要创建一个新连接。你可以找到许多如何操作的示例,包括MSDN

编辑:

有一个很好的答案可以解决这个问题:ExecuteReader requires an open and available Connection. The connection's current state is Connecting

但是如果你真的需要它,可以使用lock避免在两个或更多线程中使用相同的连接(实际上这是错误的,请参见上面的链接):

lock(_conn)
{
    DataTable dt = new DataTable();
    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
    {
        sqlDataAdapter.Fill(dt);
    }
}

我已将 if (_conn.State == ConnectionState.Closed) _conn.Open(); 替换为 if (_trans == null) {_conn = new SqlConnection(Utility.Connect); _conn.Open(); } 但问题仍未解决。 - Larry Dinh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接