Access 登录代码问题

Posted

技术标签:

【中文标题】Access 登录代码问题【英文标题】:Troubles with code for login on Access 【发布时间】:2014-01-11 19:28:33 【问题描述】:

我是 VB 脚本和任何类型的脚本的新手,但我学得很快。

我在各种辅助工具的帮助下开发了一个使用脚本的 Access 数据库。

我开发了以下脚本作为登录屏幕的一部分。

Private Sub cmdLogin_Click()

    Dim dbs As Database
    Dim rstUserPwd As Recordset
    Dim bFoundMatch As Boolean

    Set dbs = CurrentDb
    Set rstUserPwd = dbs.OpenRecordset("qryUserPwd")

    bFoundMatch = False

    If rstUserPwd.RecordCount > 0 Then
        rstUserPwd.MoveFirst

        ' check for matching records
        Do While rstUserPwd.EOF = True
            If rstUserPwd![UserName] = frmLogin.txtUsername.Value And rstUserPwd![Password] = frmLogin.txtPassword.Value Then
                bFoundMatch = True
                Exit Do
            End If
            rstUserPwd.MoveNext
        Loop

    End If

    If bFoundMatch = True Then
        'Open the next form here and close this one
        DoCmd.Close acForm, Me.Name
        DoCmd.OpenForm "frmNavigation"

    Else
        '
        MsgBox "Incorrect Username or Password"

    End If

    rstUserPwd.Close

End Sub

即使我输入了正确的用户名和密码,我还是会弹出“用户名或密码不正确”消息。谁能帮忙告诉我我做错了什么。如果需要,我可以添加数据库的副本。

【问题讨论】:

@PankajJaju 这是MS Access中使用的vba方法来表示dao中当前打开的数据库。请参阅this article 了解更多信息。 【参考方案1】:

仔细考虑这一行的逻辑......

Do While rstUserPwd.EOF = True

这对 VBA 说,“在条件为真时运行此块中的代码”。但是,当您第一次遇到该行时,记录集的当前行是第一行(MoveFirst 的结果)。因此EOF 为 False,由于 False 不等于 True,Do While 循环中的代码不会运行。

我的第一个猜测是你想要这样的东西来控制循环。

Do While Not rstUserPwd.EOF

该更改可能会使您的代码按您的预期工作。然而,这种方法比必要的更复杂。您可以使用DCount 表达式,而不是打开记录集并遍历行来检查用户名和密码是否匹配。

【讨论】:

【参考方案2】:

我假设用户名和密码都是字符串值,并建议更改您的代码如下:

Dim sSql As String
Dim rstUserPwd As DAO.Recordset
Dim bFoundMatch As Boolean

sSql = "Select * from qryUserPwd Where UserName='" & Nz(frmLogin.txtUsername, "") & "' And Password = '" & Nz(frmLogin.txtPassword, "") & "'"
Set rstUserPwd = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)

If Not (rstUserPwd.BOF And rstUserPwd.EOF) Then
    bFoundMatch = True
End If
rstUserPwd.Close: Set rstUserPwd = Nothing


If bFoundMatch = True Then
    'Open the next form here and close this one
    DoCmd.Close acForm, Me.Name
    DoCmd.OpenForm "frmNavigation"

Else
    '
    MsgBox "Incorrect Username or Password"

End If

【讨论】:

【参考方案3】:

你也可以使用这个 1 班轮:

bFoundMatch =  DCount("*", "qryUserPwd", "UserName = '" & frmLogin.txtUsername & "' And Password = '" & frmLogin.txtPassword & "'") > 0 

【讨论】:

以上是关于Access 登录代码问题的主要内容,如果未能解决你的问题,请参考以下文章

access登录校验代码二

MS Access / SQL Server 自动登录

使用 Oracle 的 ODBC 链接表登录 Access 2007

MS Access - 在表单之间传递登录信息

这个php登录代码有啥问题? [关闭]

防止用户绕过 MS Access 上的登录表单