SqlDataReader始终读为false

时间:2017-05-07 04:13:00

标签: sql-server vb.net visual-studio

我无法弄清楚为什么这个功能会导致错误,即使它看似正确。

这没有什么不妥。任何解决方案?

连接字符串或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 = MORGAN\SQLEXPRESS; 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

1 个答案:

答案 0 :(得分:0)

不要在Form_Load中设置参数值。此时他们只是空字符串。在设置.CommandText属性后设置参数值

虽然我在这里,但是让我们说用户在第一次尝试时错误输入了密码。此代码将在第二次尝试时始终失败 - 即使他们已更正密码 - 因为您已经处理了连接。在.Net中,最佳做法是在大多数情况下使用全新的连接对象(也包含在Using块中),以便您可以避免此类问题并利用连接池。

最后,此代码暗示您以纯文本格式存储密码,而不是使用salted哈希。这是如此令人难以置信的错误,我甚至不会留下示例代码显示其他修复,因为我不想留下用户名/密码检查的例子让其他人看到不要涉及散列密码。