“ExecuteReader requires an open and available Connection. The connection's current state is closed.” on WebForm [closed]

大憨熊 提交于 2019-12-13 10:29:44

问题


I am wiorking on a web application when i click on to fetch data from database i get the following error:

ExecuteReader requires an open and available Connection. The connection's current state is closed.

ExecuteReader requires an open and available Connection. The connection's current state is closed.

I declare my connection on a seperate class as the following:

public Database()
{
    valid = false;

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

Where i get the error:

and i call it from a WebForm. Why do i get this error when the connection is already open (I used to use odbc connection and it works fine, however the SqlConnection is not working)

What is the reason?


回答1:


SQL connection is open within using scope only:

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

So put your command(s) into the using scope:

  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


来源:https://stackoverflow.com/questions/36179589/executereader-requires-an-open-and-available-connection-the-connections-curre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!