【问题标题】:"ExecuteReader requires an open and available Connection. The connection's current state is closed." on WebForm [closed]“ExecuteReader 需要一个打开且可用的连接。连接的当前状态为关闭。”在 WebForm [关闭]
【发布时间】:2016-03-23 13:30:30
【问题描述】:

当我点击从数据库中获取数据时,我正在使用 Web 应用程序,我收到以下错误:

ExecuteReader 需要一个打开且可用的连接。连接的当前状态为关闭。

ExecuteReader 需要一个打开且可用的连接。这 连接的当前状态为关闭。

我在一个单独的类中声明我的连接如下:

public Database()
{
    valid = false;

    using (connection = new SqlConnection(connectionString))       
    {                  
        connection.Open();
    }    
}

我在哪里得到错误:

我从 WebForm 调用它。为什么连接已经打开时会出现此错误(我曾经使用 odbc 连接并且它工作正常,但是 SqlConnection 不工作)

是什么原因?

【问题讨论】:

  • 我没有看到对 ExecuteReader 的调用:请显示将重新创建您的问题的代码。
  • 您能否将代码发布到您实际遇到异常的位置?如果您可以清理您发布的代码(例如删除注释掉的部分),那就太好了。
  • Why do i get this error when the connection is already open 我同意,这令人难以置信,因为没有实际调用,甚至没有实例化 SqlDataReader
  • using 块会自动为你关闭连接。从您的代码中不清楚您是如何使用它的。
  • 您有 SQL 注入问题。始终使用参数。

标签: c# sql asp.net .net .net-4.0


【解决方案1】:

SQL 连接仅在 using 范围内打开:

  using (var connection = new SqlConnection(connectionString)) {
    connection.Open(); // open here
    ...
  } // close here

所以把你的命令放到using范围内:

  using (var connection = new SqlConnection(connectionString)) {
    connection.Open(); 

    // command creation and execution should be within connection "using" scope
    using (var q = new SqlCommand()) {
      q.Connection = connection;
      ...

      // reader should be within command "using" scope
      using (var reader = q.ExecuteReader()) {
        ...
      }
    }  
    ...
  } // close here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多