如何select其中之一table访问

How to select either one table to access

我有两个 table,其中 table_staff 和 table_customer,我想做任何一个用户都可以使用他们的数据(id 和密码)登录,下面是我的代码单击 "Send" 按钮时,它不起作用。有人发现我的错误吗?

Private Sub btn_send_Click(sender As Object, e As EventArgs) Handles btn_send.Click

        Dim mysql As String = "SELECT (SELECT count(*) as num_matches FROM tbl_staff where staff_id = """ & txt_name.Text & """ And staff_pwd = """ & txt_pwd.Text & """ ) As 1, (SELECT count(*) as num_matches FROM tbl_customer where customer_id = """ & txt_name.Text & """ And customer_pwd = """ & txt_pwd.Text & """ ) As 2"
        Dim mydatatable As New DataTable
        Dim myreader As New OleDb.OleDbDataAdapter(mysql, myconnection)
        myreader.Fill(mydatatable)
        Dim num_matches As String = mydatatable.Rows(0).Item("num_matches")
        If num_matches = 1 Or num_matches = 2 Then
            frm_mainmenu_a146292.Show()
            Me.Hide()
        Else
            txt_name.Text = ""
            txt_pwd.Text = ""
            MsgBox("Incorrect Username or Password")
        End If

End Sub

首先,您应该参数化您的 SQL(我将提供一个示例)。这将保护您免受 SQL 注入攻击,并且如果用户输入一个字符(如引号)中断 SQL,它将防止您的查询崩溃。

    Using conn As New OleDb.OleDbConnection("Your Connection String")
        conn.Open()

        Using cmd As OleDb.OleDbCommand = conn.CreateCommand
            cmd.CommandText = <string>
                                  select staff_id as [id] from tbl_staff where staff_id = @username and staff_pwd = @password
                                  union
                                  select customer_id as [id] from tbl_customer where customer_id = @username and customer_pwd = @password
                              </string>
            cmd.Parameters.AddWithValue("@username", txt_name.Text)
            cmd.Parameters.AddWithValue("@password", txt_pwd.Text)

            Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader

            If dr.HasRows = True Then
                ' Their login was succesful
            Else
                ' Login failure
            End If

            dr.Close()
        End Using

        conn.Close()
    End Using

旁注,相关但不相关,如果您有办法,您可能想要加密正在存储的密码。

  1. 我不确定您使用的是哪个数据库引擎,但您通常不能使用数字列名称,如“1”和“2”。请改用 "S" 和 "C"。
  2. 您可能必须在 SQL 文本中使用单引号,而不是在字面值周围使用双引号。
  3. 您需要访问 2 个列值,而不是从记录集中检索单个值到 num_matches。例如 Staff_Matches = mydatatable.rows(0).Item("S")Customer_Matches = mydatatable.rows(0).Item("C")。然后检查其中一个是否大于0.