vb.net已经有一个与此Connection关联的打开DataReader,必须先关闭它

时间:2015-10-06 13:18:04

标签: vb.net

我在vb.net中有这个代码(保存在pastebin中):http://pastebin.com/4hvMyMPb

第131行(reader = myCommand.ExecuteReader)我收到错误

There is already an open DataReader associated with this Connection which must be closed first.

但是在这行代码之上没有任何其他内容可以导致问题。

我甚至尝试将connreader更改为conn6reader6,但我收到完全相同的错误消息

2 个答案:

答案 0 :(得分:1)

在关闭连接之前放置reader.Close()

答案 1 :(得分:0)

默认情况下,连接一次只能有一个打开的DataReader。当您完成任何DataReader时,您必须在其上调用Close。如果您在整个程序中共享连接但未执行此操作,则会遇到此问题。

您可以通过连接字符串实现MultipleActiveResultSets但这只应在您打算这样做时完成,而不是修复不再使用的悬挂式阅读器。

https://msdn.microsoft.com/en-us/library/h32h3abf(v=vs.110).aspx

更好的方法是使用这样的模式来清理一切:

        ' Using Statements will handle closing and disposing
    Using conn As New SqlConnection("server=YourServer;database=YourDatabase;trusted_connection=yes;")
        conn.Open()

        Using cmd As SqlCommand = conn.CreateCommand
            cmd.CommandText = "select * from yourtable"

            ' The reader doesn't implement IDisposeable BUT this will close the reader 
            ' even in the case of exception
            Using dr As SqlDataReader = cmd.ExecuteReader

                While dr.Read
                    ' Do what you need to do with your DataReader
                    Dim buf As String = dr("myField")

                End While

            End Using

        End Using

        ' The using should call close I always close via Dispose out of habit
        conn.Close()
    End Using