已经有一个与此Connection相关联的开放DataReader,必须首先关闭VB.NET

时间:2013-03-05 08:06:15

标签: vb.net

我收到此错误消息

  

"已经有一个与此Connection关联的开放DataReader   必须先关闭"

请帮帮我 我的代码是:

Public Sub update_qty(ByVal qry1 As String) 
        Dim dr As MySqlDataReader 'SQLiteDataReader 
        Dim comm As MySqlCommand 'SQLiteCommand 


        Try

            comm = New MySqlCommand(qry1, conn)
            dr = comm.ExecuteReader()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Do While dr.Read()
            exe_query("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
        Loop

        dr.Close()
End Sub

Public Sub exe_query(ByVal qry As String) As String 

        Dim cmd As MySqlCommand 

        Try
            cmd = New MySqlCommand(qry, conn)
            cmd.ExecuteNonQuery()


        Catch ex As MySqlException
            MessageBox.Show(ex.ToString)      
        End Try

 End Sub

1 个答案:

答案 0 :(得分:4)

您的问题是您的代码打开了DataReader,然后在SqlCommand读取时执行DataReader

尝试更改此行:

 dr = comm.ExecuteReader()

为:

 dr = comm.ExecuteReader(CommandBehavior.CloseConnection)

更多:DataReader CommandBehavior

或更改连接字符串以启用MARS(多个活动结果集)。 此设置允许在同一连接上检索多个只进,只读结果集。

例如:

connectionString=
"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|Northwind.MDF;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True"

更多:MARS

修改

由于不支持MARS关键字,请尝试将代码更改为:

Public Sub update_qty(ByVal qry1 As String) 
        Dim dr As MySqlDataReader 'SQLiteDataReader 
        Dim comm As MySqlCommand 'SQLiteCommand 


        Try

            comm = New MySqlCommand(qry1, conn)
            dr = comm.ExecuteReader()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Dim myList As New List(Of String)

        Do While dr.Read()
            myList.Add("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
        Loop

        dr.Close()
End Sub

Public Sub exe_query(myList As List(Of String)) 

        Dim cmd As MySqlCommand 

        For Each query As String In myList
            Try
                cmd = New MySqlCommand(query, conn)
                cmd.ExecuteNonQuery()

            Catch ex As MySqlException
                MessageBox.Show(ex.ToString)      
            End Try
        Next

 End Sub

而是同时执行DataReader.Read - > SqlCommand.ExecuteNonQuery,此代码将首先读取所有数据,然后运行SqlCommand.ExecuteNonQuery