1

我收到此错误消息

“已经有一个打开的 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
4

1 回答 1

4

您的问题是您的代码打开 aDataReader然后SqlCommandDataReader读取时执行

尝试更改此行:

 dr = comm.ExecuteReader()

到:

 dr = comm.ExecuteReader(CommandBehavior.CloseConnection)

更多:DataReader 命令行为

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

例如 :

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

更多:火星

编辑

由于不支持 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

于 2013-03-05T08:11:19.020 回答