0

嗨,我是 Visual Basic 的新手。我有一个按钮,当它被点击时,它会通过用户输入的 ID 找到学生,并将数据输出到文本字段。我不太确定我这样做是否正确。因为我收到此错误 [图片] >> http://img812.imageshack.us/img812/7650/gq0z.png

顺便说一句,到目前为止,这是我的代码。有人能帮助我吗?谢谢!

        cmd.CommandText = "Select * from Student where Student_id = '" & id.Text & "'"
        cmd.Connection = db

        dr = cmd.ExecuteReader

        Try
            dr.Read()
            id.Text = dr.GetValue(0)
            Lname.Text = dr.GetValue(1)
            Fname.Text = dr.GetValue(2)
            Mname.Text = dr.GetValue(3)
            datet.Text = dr.GetValue(4)
            age.Text = dr.GetValue(5)
            male.Text = dr.GetValue(6)
            female.Text = dr.GetValue(7)
            status.Text = dr.GetValue(8)
            staddress.Text = dr.GetValue(9)
            cityAdd.Text = dr.GetValue(10)
            dr.Close()

        Catch ex As Exception
            MsgBox("" + ex.Message)
            dr.Close()
        End Try
4

3 回答 3

4
cmd.CommandText = "Select * from Student where Student_id = '" & id.Text & "'"

改成:

if IsNumeric(id.text) Then
cmd.CommandText = "Select * from student where Student_id=@p1"
cmd.Prepare
cmd.Parameters.AddWithValue("@p1", id.text)
dr = cmd.ExecuteReader
....
Else
Exit Sub
End If

你可以这样做,或者

 dr = cmd.ExecuteReader

    Try
       with dr
        .Read()
        id.Text = .GetValue(0)
        end with
        dr.Close()

或者

with dr
    .read
    id.text = .item("id")
    .close

更容易阅读......

于 2013-10-28T18:49:27.650 回答
1

首先添加一个参考,如果你使用的是 MySQL 数据库,那就赌一把。班上

Dim Connection As MySqlConnection
Dim command As MySqlCommand

把它放到你的文本框中

Connection = New MySqlConnection
Connection.ConnectionString = "Server=localhost;port=3306;userid=root;password=root;database=databasename"
Dim reader As MySqlDataReader

根是默认的

Try
  Connection.Open()
  Dim query As String
  query= "Select * from Databasename.tablename where fieldname='" & textbox1.text & "'"
  Command = New MySqlCommand(query, Connection)
  reader = Command.ExecuteReader
  While reader.Read
    Dim sname As String
    sname = reader.GetString("Fieldname")
    textbox1.Items.Add(sname)
  End While
  Connection.Close()
Catch e MySqlException
  MsgBox (ex.Message)
Finally
  Connection.Dispose
End Try
于 2016-01-05T08:32:54.270 回答
0

如果您使用的是 Mysql 数据库,请先添加引用。添加MySql 数据库的引用

  1. 转到您的解决方案资源管理器并右键单击您的项目名称
  2. 查找添加->引用

    将打开一个窗口

  3. 在该窗口中,在“程序集”下选择框架。
  4. 在右侧会有一个列表查找并选择 Microsoft.VisualBasic.Compatability.Data
  5. 在扩展中,找到并添加 MySql.Data 和 MSDATASRC
  6. 点击确定
于 2018-02-27T02:19:46.893 回答