我无法弄清楚为什么该功能会导致错误,即使它看起来正确。
这没什么错。有任何解决方案吗?
连接字符串或SQL相关功能没有错。我的功能有问题。我使用SQL Server。
ESEMKABank > Employee
:
EmployeeId int IDENTITY(1, 1)
Username nvarchar(64)
Password nvarchar(64)
FullName nvarchar(64)
RoleId int -- <-- FOREIGN KEY
vb.net:
Imports System.Data.SqlClient
Public Class Form_Login
'Dimensions
Dim theConnection As New SqlConnection
Dim theCommand As New SqlCommand
Dim theDataReader As SqlDataReader
Dim theDataAdapter As New SqlDataAdapter
'Initialization
Private Sub Form_Login_Load(sender As Object, e As EventArgs) Handles Me.Load
theConnection.ConnectionString = "SERVER = MORGANSQLEXPRESS; DATABASE = ESEMKABank; INTEGRATED SECURITY = TRUE;"
'Parameterize
theCommand.Parameters.Add("@Username", SqlDbType.VarChar).Value = Me.TextBox_Username.Text
theCommand.Parameters.Add("@Password", SqlDbType.VarChar).Value = Me.TextBox_Password.Text
End Sub
'Login
Private Sub Button_Login_Click(sender As Object, e As EventArgs) Handles Button_Login.Click
If Me.TextBox_Username.Text = "" Or Me.TextBox_Password.Text = "" Then
Me.PictureBox_Wrong.Visible = True
Else
Using theDataReader
'Declaration
theCommand.Connection = theConnection
theCommand.CommandText = "SELECT Username, Password FROM Employee WHERE Username = @Username AND Password = @Password"
theConnection.Open()
theDataReader = theCommand.ExecuteReader()
If theDataReader.Read() Then
'Dispose!
theCommand.Dispose()
theConnection.Close()
SqlConnection.ClearPool(theConnection)
Me.PictureBox_Wrong.Visible = False
Else
'Dispose!
theCommand.Dispose()
theConnection.Close()
SqlConnection.ClearPool(theConnection)
Me.PictureBox_Wrong.Visible = True
End If
End Using
End If
End Sub
End Class
不要在form_load中设置参数值。在这一点上,它们只是空字符串。在之后设置参数值您设置.CommandText
属性。
当我在这里时,假设用户在第一次尝试时将密码错误类型。此代码将在第二次尝试中始终失败;即使他们纠正了密码&mdash;因为您已经处理了连接。在.NET中,最好的做法是在大多数情况下使用一个全新的连接对象(也包含在Using
块中(,以便您可以避免此类问题并利用连接池。
最后,此代码意味着您将密码存储在纯文本中,而不是使用盐的哈希。这是非常错误的错误,以至于我什至不会留下示例代码显示其他修复程序,因为我不想留下对其他人进行用户名/密码检查的示例,以查看不涉及哈希的密码。