0

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

なぜシステムは常にそのメッセージを返すのですか?

私はサブを持っています:

Private Sub Initialization()    

    If myCEConnection.State = ConnectionState.Closed Then '--> *1
        Try
            myCEConnection.Open()
        Catch ex As Exception

        End Try
    End If

    Dim reader As SqlCeDataReader
    Dim myCommand As SqlCeCommand = myCEConnection.CreateCommand()

    myCommand.CommandText = "Command goes here"
    Try
        reader = myCommand.ExecuteReader() 
    Catch ex As Exception '--> *2

    End Try

    myCEConnection.Close()
End Sub

そして、私はこのサブからその関数を呼び出しました:

Public myCEConnection As New SqlCeConnection("Connection String Goes Here")

Private Sub Report()
    If myCEConnection.State = ConnectionState.Closed Then '--> *1
        Try
            myCEConnection.Open()
        Catch ex As Exception

        End Try
    End If

    Initialization()

    myCEConnection.Close()
End Sub

行にブレークポイントを設定しようとすると*1、システムはを返しますmyCEConnection.State = Open {1}。しかし、ブレークポイントを実行し続けると、次のよう*2になります。ExecuteReader requires an open and available Connection. The connection's current state is Closed.

ここに画像の説明を入力してください

コードの何が問題になっていますか?

注:クラスのすべてのサブ/関数にはIf myCeConnection.State = .....、接続がすでに開いているかどうかを確認する部分が常にあります。たぶんこれが問題を引き起こしたのかもしれませんが、私にはよくわかりません。

4

1 に答える 1

1

接続とコマンドを関連付ける必要があります。

myCommand.Connection = myCEConnection

コードを次のように変更することも検討してください。

Dim reader As SqlCeDataReader

Using myCEConnection As New SqlCeConnection("Connection String Goes Here")
  myCEConnection.Open()
  Using myCommand As SqlCeCommand = myCEConnection.CreateCommand()
    myCommand.Connection = myCEConnection
    myCommand.CommandText = "Command goes here"
    reader = myCommand.ExecuteReader()
  End Using
End Using

Try-Catch は実際には必要ありません。私の推測では、最初myCEConnection.Open()は例外がスローされていますが、Try-Catch が原因でそれが表示されることはありません。

于 2012-05-05T03:57:53.917 に答える