我正在尝试使用mysql事务保存多行数据,但是当我在指定的行执行此代码时出现错误
Using conn As New MySqlConnection(connStr)
conn.Open()
Using sqlTrans As MySqlTransaction = conn.BeginTransaction()
Try
Dim bHasRows As Boolean
dim sSql as string
For Each kv As KeyValuePair(Of String, String) In dicOpts
If String.IsNullOrEmpty(kv.Key) Then Continue For
String.format("Select * FROM Options WHERE name = '{0}';",kv.Key)
Using cmd As New MySqlCommand(qb.GetQuery, conn)
bHasRows = cmd.ExecuteReader().HasRows
End Using
If bHasRows Then
ssql=String.format("UPDATE Options SET value ='{0}' WHERE name = '{1}';", kv.Value,kv.Key)
Else
ssql=String.format("INSERT INTO Options(name,Value) values('{0}','{1}';",kv.Key, kv.Value)
End If
Using cmd As New MySqlCommand(qb.GetQuery, conn)
cmd.ExecuteNonQuery() // <----- This is the error line
End Using
Next
sqlTrans.Commit()
Catch ex As Exception
sqlTrans.Rollback()
Throw
Finally
End Try
End Using
我得到的错误
已经有一个与此Connection关联的开放DataReader 必须先关闭
正如您所看到的,每次使用
都会关闭阅读器答案 0 :(得分:1)
这是你走错的地方:
bHasRows = cmd.ExecuteReader().HasRows
在datareader上使用Using
:
Using dr = cmd.ExecuteReader()
bHasRows = dr.HasRows
End Using
答案 1 :(得分:1)
这正是消息所读取的内容。 bHasRows = cmd.ExecuteReader().HasRows
打开DataReader并且不会关闭。正确的形式是
Using cmd As New MySqlCommand(qb.GetQuery, conn)
Dim r = cmd.ExecuteReader()
bHasRows = r.HasRows
r.Close()
End Using