我正在制作一个mysql sigin表单并且我试图使用我的用户表来控制登录访问,但每当我输入任何随机字母时它都会登录而不会显示错误,即它是一个无效的用户名。
这是我到目前为止所做的:
Imports MySql.Data.MySqlClient
Public Class frmLogin
Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
Application.Exit()
End Sub
Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myConnString As String
Dim UserID As String
myConnString = "server=" & My.Settings.HostIP & ";" _
& "user id=" & My.Settings.Username & ";" _
& "password=" & My.Settings.Password & ";" _
& "database=attendance"
conn.ConnectionString = myConnString
Try
conn.Open()
myCommand.Connection = conn
myCommand.CommandText = "SELECT user_bannerid FROM user WHERE BINARY username = ?Username"
myCommand.Parameters.Add("?Username", txtUsername.Text)
UserID = myCommand.ExecuteScalar
conn.Close()
Dim mainForm As New frmMain
mainForm.UserID = UserID
mainForm.connectionString = myConnString
mainForm.Show()
Me.Hide()
Me.Close()
Catch myerror As MySqlException
MessageBox.Show("Invalid User. Please Enter Your Correct Username")
conn.Dispose()
End Try
End Sub
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.AcceptButton = cmdLogin
Me.CancelButton = cmdCancel
End Sub
End Class
答案 0 :(得分:2)
这是因为您在关闭表单之前没有测试userid的值。
您还需要使用声明来确保所有一次性物品都得到妥善处理。
这是一个解决这两个问题的重写:
Try
Using conn As New MySqlConnection
Using myCommand As New MySqlCommand
Dim myConnString As String
Dim UserID As String
myConnString = "server=" & My.Settings.HostIP & ";" _
& "user id=" & My.Settings.Username & ";" _
& "password=" & My.Settings.Password & ";" _
& "database=attendance"
conn.ConnectionString = myConnString
conn.Open()
myCommand.Connection = conn
myCommand.CommandText = "SELECT user_bannerid FROM user WHERE BINARY username = ?Username"
myCommand.Parameters.Add("?Username", txtUsername.Text)
Dim oUserID As Object
oUserID = myCommand.ExecuteScalar
conn.Close()
If oUserID IsNot DBNull.Value AndAlso Not String.IsNullOrEmpty(oUserID) Then
Dim mainForm As New frmMain
mainForm.UserID = UserID
mainForm.connectionString = myConnString
mainForm.Show()
Me.Hide()
Me.Close()
Else
MessageBox.Show("Invalid User. Please Enter Your Correct Username")
End If
End Using
End Using
Catch myerror As MySqlException
MessageBox.Show("SQL Error" & myerror.ToString())
End Try