2016-03-23 813 views
-1

データベースからデータを取得するために、をクリックしたときにWebアプリケーションを起動しています。次のエラーが表示されます。"ExecuteReaderには開いている使用可能な接続が必要です。接続の現在の状態は閉じています。 WebFormの場合

ExecuteReaderには開いている接続が必要です。接続の現在の状態は閉じられています。

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

は、私は、次のように別々のクラスに私の接続を宣言します。

enter image description here

と私はWebフォームから呼び出す:私はエラーを取得

public Database() 
{ 
    valid = false; 

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

。接続が既に開いているときにこのエラーが発生するのはなぜですか(私はodbc接続を使用していましたが、正常に動作しますが、SqlConnectionは機能しません)

何故ですか?

+2

:してください問題を再現するコードを表示します。 – Richard

+0

実際に例外が発生しているコードを投稿してください。また、投稿したコードをクリーンアップすることもできます(コメントアウトした部分を削除するなど)。 –

+0

'接続が既に開いているときにこのエラーが出るのはなぜですか?'実際の呼び出しや 'SqlDataReader'のインスタンス化さえないので、信じられないほど困惑しています。 – CodingGorilla

答えて

1

SQL接続のみスコープを使用して内で開かれている:

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

だからあなたコマンド(複数可)usingスコープに入れて:私はExecuteReader` `への呼び出しを見ない

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 
関連する問題