我在从 mysql 数据库收集数据并将其放入 DataView 控件时遇到了此错误...这是我的代码:
Private Function PopulateActivity()
Dim loginStatement As String = "SELECT * FROM activity WHERE id = @userid"
Dim cmd As MySqlCommand = New MySqlCommand(loginStatement, mainconn)
cmd.Parameters.AddWithValue("@userid", LoggedInUser.ID)
Dim drMyAcount As MySqlDataReader = cmd.ExecuteReader()
Dim rowCount As Integer = 0
Dim rowAmount As Integer = 0
'gets count of rows returned from mysql query'
Using dt As New DataTable
dt.Load(drMyAcount)
rowAmount = dt.Rows.Count
End Using
'adds an entry for each item returned from the mysql query'
Do While rowCount < rowAmount
drMyAcount.Read() 'HERE IS WHERE ERROR OCCURS'
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1
Loop
drMyAcount.Close()
Return 0
End Function
我不知道为什么会这样,但它给了我一个“阅读器关闭时无效的尝试阅读”错误:
drMyAccount.Read()
行...
对于这个主题的任何帮助,我将不胜感激!非常感谢...
最佳答案
取出dt.Load()
,并在使用 datareader 之前对行进行计数。 DataReader 有一个内置属性 .HasRows
if (drMyAcount.HasRows)
while (drMyAcount.Read())
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1 //you can still count rows in the loop
Loop
关于Mysql & Vb.net 'Invalid Attempt to Read when reader is closed',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20572351/