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 回答