繁体   English   中英

如何从数据库获取数据到VB.net上的文本框

[英]How to get data from database to textbox on VB.net

您好,我在Visual Basic中是新的。 我有一个按钮,单击该按钮时,它将通过用户输入的ID查找学生,并将数据输出到文本字段。 我不确定我是否做对了。 因为我遇到此错误[image] >> 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
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

更容易阅读...

首先添加一个引用,如果您使用的是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

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

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

    将会打开一个窗口

  3. 在该窗口的“程序集”下,选择框架。
  4. 在右侧将找到一个列表,然后选择Microsoft.VisualBasic.Compatability.Data
  5. 在扩展中,找到并添加MySql.Data和MSDATASRC
  6. 点击确定

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM