簡體   English   中英

如何檢查用戶是否存在於 mysql 數據庫 vb.net

[英]How to check if user exists in mysql database vb.net

我有一些代碼要從 mysql 數據庫中讀取,但我只是想知道如何修改它以查看表中是否存在用戶?

謝謝

    Private Sub GetDBData()
    Try
        'prepare connection query 
        strQuery = "SELECT users.Username, users.Password " & _
        "FROM users " & _
        "WHERE Username='User'"
        SQLCmd = New MySqlCommand(strQuery, dbCon)
        'open db and start query
        dbCon.Open()
        DR = SQLCmd.ExecuteReader
        While DR.Read
            MysqlData.Text = MysqlData.Text & DR.Item("Username") & Space(10) & DR.Item("Password") & vbCrLf
        End While
        'done so closing db
        DR.Close()
        dbCon.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

一種簡單的方法是進行如下查詢:

SELECT COUNT(*) FROM users WHERE Username='user123';

你運行它,取回它返回的值,如果它是 0 則用戶不存在。 如果它是 1,那么他就存在,如果它大於 1,那么就會出現問題(您有多個用戶使用相同的用戶名)。

我的 VB 相當生疏,但這是它的要點;

Private Sub GetDBData()
Try
    'prepare connection query 
    strQuery = "SELECT users.Username, users.Password " & _
    "FROM users " & _
    "WHERE Username='User'"
    SQLCmd = New MySqlCommand(strQuery, dbCon)
    'open db and start query
    dbCon.Open()
    DR = SQLCmd.ExecuteReader

    If DR.HasRows Then

        While DR.Read
            MysqlData.Text = MysqlData.Text & DR.Item("Username") & Space(10) & DR.Item("Password") & vbCrLf
        End While
    Else
        'COMMENT: Your user didn't exist
    End If

    'done so closing db

    'COMMENT: move to a finally() section and check objects are not null before closing
    DR.Close()
    dbCon.Close()

Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

結束子

使用帶parameters command來避免 SQL 注入。 如果您只是通過進行一些比較檢查用戶名是否存在那么一種策略是創建一個返回布爾值的函數。 以下是基於您的需要的示例代碼。

Private Function IsUserExist(userName as string) AS Boolean

        Dim returnValue as boolean = false

        strQuery = "SELECT COUNT(*)"
        strQuery &= "FROM users "
        strQuery &= "WHERE Username = @xUserName "

        Using xConn as new MySQLCnnection("connectionStringHere")
            Using xComm as New MySQLCommand()
                With xComm
                    .Connection = xConn
                    .CommandText = strQuery
                    .CommandType = CommandType.Text
                    .Parameters.AddWithValue("@xUserName", userName)
                End With
                Try
                    xConn.Open()
                    If CInt(xComm.ExecuteScalar()) > 0 Then
                        returnValue = true
                    End If
                Catch ex as MySQlException
                    MsgBox(ex.Message)
                    returnValue = false
                Finally
                    xConn.Close
                End Try
            End Using
        End Using

        return returnValue
End Sub

修改一下? 錯太多了。 無 using 塊、異常吞咽和潛在的 sql 注入攻擊。

類似的東西(我不做 VB 但基本的想法是合理的)

Private Function UserExists(argUser As string) As Bool
  strQuery = "SELECT Username FROM users WHERE Username=?User"
  Using SQLcmd = New MySqlCommand(strQuery, dbCon)
    SQLCmd.Parameters.Add("?User",argUser)  
    dbCon.Open()
    Using reader = SQLCmd.ExecuteReader()
      return reader.Read()
    End Using
  End Using
End Function

如果是我,我也會實例化一個連接,而不是從您當前所在的任何位置(在 using 塊中)獲取它。

Protected Sub btnlogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlogin.Click
    Dim myAdapter As New MySqlDataAdapter
    Dim myCommand As New MySqlCommand
    Dim myData As MySqlDataReader
    Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=name;User ID=root;Password=pwd;")

    Dim loginstring As String = "SELECT uname,password,type FROM logindetails WHERE uname = '" + txtuname.Text + "' AND password = '" + txtpwd.Text + "' "
    Try
        conn.Open()
    Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
        MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
    End Try

    myCommand.Connection = conn
    myCommand.CommandText = loginstring
    myAdapter.SelectCommand = myCommand
    myData = myCommand.ExecuteReader

    If myData.HasRows = 0 Then
        MsgBox("Invalid Credentials", MsgBoxStyle.Critical)
    Else
        Response.Redirect("Adminhome.aspx")
        MsgBox("Logged in as " & txtuname.Text & ".", MsgBoxStyle.Information)
    End If
    conn.Close()
End Sub

它很簡單...

在進入 while 循環之前,聲明一個整數並將其設置為零。 在開始獲取數據之前的 while 循環中,將該整數設置為 1。 在 while 之外但在 catch 之前,放置一個 if 語句來通知您當整數仍然為零時,這意味着 db 中沒有數據。 像這樣的東西...

Private Sub GetDBData()
    Try
        'prepare connection query 
        strQuery = "SELECT users.Username, users.Password " & _
        "FROM users " & _
        "WHERE Username='User'"
        SQLCmd = New MySqlCommand(strQuery, dbCon)
    'open db and start query
    dbCon.Open()
        DR = SQLCmd.ExecuteReader
        Dim x As Integer = 0
        While DR.Read
        x = 1
        MysqlData.Text = MysqlData.Text & DR.Item("Username") & Space(10) & DR.Item("Password") & vbCrLf
    End While
    'done so closing db

    DR.Close()
    dbCon.Close()

   if x = 0
        Messagebox.Show("Record not found")
   End If
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

結束子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM