[英]Validating Username And Password from MySQL
我正在尋找驗證VB中用戶名和密碼的代碼。
Private Sub LoginBtn_Click(sender As Object, e As EventArgs) Handles LoginBtn.Click
Try
con.Open()
com = New MySqlCommand("SELECT id FROM accounts WHERE uname='" & txtuname.Text & "'", con)
reader = com.ExecuteReader
If reader.HasRows = True Then
com = New MySqlCommand("SELECT id FROM accounts WHERE pword = '" & txtpword.Text & "' AND uname='" & txtuname.Text & "'", con)
If reader.HasRows = True Then
Form3.Show()
Else
MsgBox("Invalid Password")
txtpword.Focus()
End If
ElseIf String.IsNullOrEmpty(txtuname.Text) Then
MsgBox("Invalid Username")
txtuname.Focus()
Else
MsgBox("New User Detected. Input Password")
Form2.Show()
End If
reader.Close()
con.Close()
Catch ex As Exception
If Not con.State = ConnectionState.Closed Then
con.Close()
End If
MsgBox(ex.ToString)
End Try
End Sub
條件如下:
我的問題是條件2。 即使pword txtbox中的數據有誤,它仍會繼續導致形成表格3,而不是顯示msgbox。
您在第二次查詢后忘記了reader = com.ExecuteReader
,即。 后
com = New MySqlCommand("SELECT id FROM accounts WHERE pword = '" & txtpword.Text & "' AND uname='" & txtuname.Text & "'", con)
因此,它僅考慮第一個查詢的輸出,而第二個查詢保持未執行狀態
你應該再打一次
reader = com.ExecuteReader
后:
com = New MySqlCommand("SELECT id FROM accounts WHERE pword = '" & txtpword.Text & "' AND uname='" & txtuname.Text & "'", con)
您剛剛檢查過它是否具有行,並且尚未更改。
您需要再次調用閱讀器,否則它將不執行第二個查詢。 正如其他人所建議的。 這樣,您的代碼似乎是針對公共應用程序的。 以此方式編寫的代碼使您容易遭受注入攻擊。 用戶可以將惡意代碼插入您的文本框,服務器可以對其進行處理。 如果在查詢中使用參數而不是文本框的.Text會更好,如下所示:
Private Sub LoginBtn_Click(sender As Object, e As EventArgs) Handles LoginBtn.Click
Try
con.Open()
com = New MySqlCommand("SELECT id FROM accounts WHERE uname=@uname, con)
With com
.Parameters.AddWithValue("@uname", txtuname.Text)
End With
reader = com.ExecuteReader
If reader.HasRows = True Then
com = New MySqlCommand("SELECT id FROM accounts WHERE pword = @pword AND uname = @uname, con)
With com
.Parameters.AddWithValue("@uname", txtuname.Text)
.Parameters.AddWithValue("@pword", txtpword.Text)
End With
reader = com.ExecuteReader
If reader.HasRows = True Then
Form3.Show()
Else
MsgBox("Invalid Password")
txtpword.Focus()
End If
ElseIf String.IsNullOrEmpty(txtuname.Text) Then
MsgBox("Invalid Username")
txtuname.Focus()
Else
MsgBox("New User Detected. Input Password")
Form2.Show()
End If
reader.Close()
con.Close()
Catch ex As Exception
If Not con.State = ConnectionState.Closed Then
con.Close()
End If
MsgBox(ex.ToString)
End Try
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.