在调用read()之前无效尝试访问字段6

时间:2014-10-07 15:51:38

标签: mysql vb.net

它试图在数据库中选择id,但它说错误: 在调用read()之前无效尝试访问字段 你能救我吗? 谢谢

     Try
        MySqlConnection.Open()
        Dim READER As MySqlDataReader
        Dim query As String
        query = " select id from mcs.student where (last_name = '" & txtlastname.Text & "' and first_name = '" & txtfirstname.Text & "' and  middle_name = '" & txtmiddlename.Text & "')"
        Dim Command As New MySqlCommand(query, MySqlConnection)
        READER = Command.ExecuteReader

        READER.Read()
        lblno.Text = READER(0)


        Dim lbl1 As String = year.Text
        Dim lbl2 As String = day.Text

        lblstudentno.Text = (String.Concat(year.Text, day.Text, lblno.Text))


    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        MySqlConnection.Dispose()

    End Try

1 个答案:

答案 0 :(得分:0)

使用 MySqlDataReader ,从 ExecuteReader 读取数据的方式不正确。您需要转换数据。试试下面的内容;​​

Dim Command As MySqlCommand = New MySqlCommand(query, MySqlConnection)

Reader = command.ExecuteReader()

lblno.Text = Reader.GetString(0) -- If Id is varchar 
lblno.Text = Reader.GetInt32(0) -- If Id is integer

或者你可以按照以下步骤进行操作;

 lblno.Text = Convert.ToString(Command.ExecuteScalar())