Mysql& Vb.net'读者关闭时无效尝试读取'

时间:2013-12-13 17:21:45

标签: 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()

...线

感谢您对此话题的任何帮助!非常感谢...

2 个答案:

答案 0 :(得分:1)

取出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

答案 1 :(得分:0)

MSDN documentation似乎没有指定,但显然DataTable.Load方法在将数据加载到表中时关闭了给定的IDataReader。因此,在您致电dt.Load(drMyAcount)后,drMyAcount将会关闭。