在调用Read()vb.net之前无法尝试访问字段

时间:2014-09-04 04:57:55

标签: vb.net

我收到此错误不是因为代码错误,而是因为我的表中没有数据

如何检查是否没有数据并将变量返回为0

这是我的代码 我正在尝试获取计数器编号,但没有记录时出现错误

Public Function GetCount()
   Dim count As Integer
   Dim cmd As New MySqlCommand
   Dim reader As MySqlDataReader = Nothing
   Conn.OpenConn()
   Dim sqlstr As String
   sqlstr = "SELECT counter FROM st_sales ORDER BY salesid DESC LIMIT 1"
   Try
    'CREATE COMMAND
     cmd = New MySqlCommand(sqlstr, Conn.Conn)

     reader = cmd.ExecuteReader()
     If reader.Read() Then
        count = reader.GetInt32(0) + 1
     Else
        MsgBox("Error")
     End If
    Finally
       reader.Close()
       Conn.CloseConn()
    End Try
    Return count
End Function

感谢任何healp

1 个答案:

答案 0 :(得分:0)

试试这个

If reader.HasRows then
 'do the counting
else
  count=0
end if