我正在尝试收集来自用户的输入,根据数据库检查它,并查看它是否存在于数据库中。如果是这样,程序应该获取每个人的姓、名和费用并输出。
代码:
Imports Mysql.Data.MySqlClient
Public Class Form1
Dim reader As MySqlDataReader
Dim command As New MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConnectionString As String
myConnectionString = "server=localhost;" _
& "uid=root;" _
& "pwd=Emma@21*GCTU;" _
& "database=dummystudents"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Dim sql As String = "SELECT idstudents FROM students WHERE idstudents = @TextBox1.Text "
command = New MySqlCommand(sql, conn)
reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
这是你的SQL代码:
SELECT idstudents FROM students WHERE idstudents = @TextBox1.Text
当idstudents
是你输入的值时,把它拿出来有什么意义?更糟糕的是,这是你所提取的全部内容,然后你这样做:
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
,这将要求您撤回至少四列。
注释中提到的修改可能会让你的代码执行,但这不是正确的方法。看起来您试图使用参数,但失败了。做那件事,但要做对,即
Dim sql As String = "SELECT idstudents, otherColumnsHere FROM students WHERE idstudents = @idstudents"
Using connection As New MySqlConnection(myConnectionString),
command As New MySqlCommand(sql, connection)
command.Parameters.Add("@idstudents", MySqlDbType.Int32).Value = CInt(TextBox1.Text)
conn.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
End Using
End Using