Mysql & Vb.net 'Invalid Attempt to Read when reader is closed'

标签 mysql vb.net

我在从 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/

相关文章:

php - 群组 , 订单 , 限额

c# - 使用 Lockbits 替换图像的颜色

vb.net - 按需显示或隐藏标题栏

mysql - 查找出现次数最多的值的正确 SQL (MYSQL) 是什么?

mysql - 两个外键引用一个表和可为空的外键

c# - 在 vb 和 c# 中调用对象类型变量的方法

c# - XElement 和 XDocument 有什么区别?

vb.net - 连接到数据库时正确声明 ConfigurationManager

php - 为什么第一次启动网站时没有 session ?

mysql - 获取每个问题,正确回答的用户数量