嗨,我是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
答案 0 :(得分:3)
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
更容易阅读....
答案 1 :(得分: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
root是默认的
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
答案 2 :(得分:0)
如果您使用的是Mysql数据库,请先添加引用。添加 MySql数据库
的参考查找add->参考
将打开一个窗口