My Connection already open but why the system said it closed?
-
05-06-2021 - |
質問
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
Why always the system returns that message?
I have a sub:
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
And I called that function from this 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
When I try to set a breakpoint to the *1
line, the system returns myCEConnection.State = Open {1}
. But when I continue to run the breakpoint, on line *2
I got: ExecuteReader requires an open and available Connection. The connection's current state is Closed.
What's wrong with the code?
Note: Every sub/function on the class always have the If myCeConnection.State = .....
part to check the connection is already open or not. Maybe this caused the problem but I'm not quite sure.
解決
You need to associate the connection and the command:
myCommand.Connection = myCEConnection
Also consider changing your code into something like this:
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
You don't really need the Try-Catch'es, and my guess is the initial myCEConnection.Open()
is throwing an exception, but you never see it because of the Try-Catch.