Imports System.Data.OleDb
Public Class LoginForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersUserDesktopthesisYBIM.accdb"
Dim conn As New OleDbConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn.ConnectionString = connstring
If conn.State = ConnectionState.Closed Then
conn.Open()
MsgBox("welcome")
Else
MsgBox("Cannot connect to database")
End If
End Sub
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim SqlQuery As String = ("SELECT * FROM tablelogin WHERE Username= @field1 AND Password=@field2")
Dim SqlCommand As New OleDbCommand
Dim Sqlrdr As OleDbDataReader
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("@field1", UsernameTextBox.Text)
.Parameters.AddWithValue("@field2", PasswordTextBox.Text)
.ExecuteNonQuery()
End With
Sqlrdr = SqlCommand.ExecuteReader()
If (Sqlrdr.Read() = True) Then
home.ShowDialog()
Me.Hide()
Else
MsgBox("wong input")
End If
End Sub
End Class
代码中有两件事需要注意,您可以进行补救。
1* 参数命名不正确。这:
.Parameters.AddWithValue("@field1", UsernameTextBox.Text)
.Parameters.AddWithValue("@field2", PasswordTextBox.Text)
应该是这样的:
.Parameters.AddWithValue("field1", UsernameTextBox.Text)
.Parameters.AddWithValue("field2", PasswordTextBox.Text)
2* 您正在执行该命令两次。从 With 语句中删除.ExecuteNonQuery()
,并更改:
Sqlrdr = SqlCommand.ExecuteReader()
自
Dim ret As Integer
ret = SqlCommand.ExecuteNonQuery()
而不是使用 Sqlrdr.Read()
,只需检查 ret 是否> 0(执行非查询返回受命令影响的行数)。