【问题标题】:Mysql & Vb.net 'Invalid Attempt to Read when reader is closed'Mysql & Vb.net '阅读器关闭时尝试读取无效'
【发布时间】:2013-12-14 01:32:32
【问题描述】:

我在从 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()

行...

我将不胜感激有关此主题的任何帮助!非常感谢...

【问题讨论】:

    标签: mysql vb.net


    【解决方案1】:

    取出 dt.Load() ,并在使用数据读取器之前计算行数。 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
    

    【讨论】:

    • 我知道 HasRows 但它不计算我需要做的行数...
    • 连接数据库两次,一次只是为了获取行数效率不是很高
    【解决方案2】:

    MSDN documentation 似乎没有指定,但显然DataTable.Load 方法在完成将数据加载到表中时会关闭给定的IDataReader。所以,一旦你调用dt.Load(drMyAcount)drMyAcount 就会被关闭。

    【讨论】:

    • 那么您对如何解决这个问题有什么想法吗?
    • 您可以执行两次命令,也可以直接从数据表中读取数据,而不是从阅读器中读取。
    猜你喜欢
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多