在 vb.net 中读取和比较 MySQL 数据库中的数据值

reading and comparing data values in MySQL database in vb.net

我正在尝试收集用户的输入,对照我的数据库检查它,看看它是否存在于数据库中。如果是,程序应该获取相应个人的姓氏、名字和费用并输出。

代码:

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