嗨我是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
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 Database,请先添加引用。添加MySql数据库的引用