VB6和.accdb数据库登录表

时间:2018-08-12 21:05:28

标签: ms-access vb6

我想知道是否有人可以帮助我解决这个问题。我有一个带有名为cboUsername的组合框和一个名为txtPassword的密码的文本框的登录表单。我有访问数据库的Employee表的表单,并用.accdb中strEmpName字段的Employee名称填充了组合框,并且在检查具有字段名strEmpPassword的同一张表的密码时遇到了问题。我要尝试的是如果密码匹配,然后允许访问该软件。除此之外,我还有一个名为strAccess的字段,该字段允许用户访问软件的某些部分。 strAccess将为“管理员”,“用户”或“只读”。谁能帮助我解决方案?我的工作代码如下:

Option Explicit
Private Sub Form_Load()
Dim db_file As String
Dim statement As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset

cboUsername.Text = "Select Username"

' Get the data.
db_file = App.Path
If Right$(db_file, 1) <> "\" Then db_file = db_file & "\"
db_file = db_file & "FluidFlo.accdb"

' Open a connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
    "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & db_file & ";" & "Persist Security Info=False"
conn.Open

' Select the data.
statement = "SELECT strEmpName FROM tblEmployees ORDER BY strEmpName"

' Get the records.
Set rs = conn.Execute(statement, , adCmdText)

' Load the results into the ComboBox
Do Until rs.EOF
    cboUsername.AddItem rs!strEmpName
    rs.MoveNext
Loop
' Close the recordset and connection.
rs.Close
conn.Close

End Sub

我希望我已经清楚我要完成的工作,并且一如既往地感谢大家!

1 个答案:

答案 0 :(得分:1)

我有一个产生Windows用户名的函数

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Function LoginName() As Variant
    Dim ret As Long
    Dim s As String * 255
    Dim pos As Long

    ret = GetUserName(s, 255)
    pos = InStr(s, vbNullChar)
    If pos <= 1 Then
        LoginName = Null
    Else
        LoginName = Left$(s, pos - 1)
    End If
End Function

使用此功能,您只需输入密码即可,而无需在ComboBox中填写用户名。

使用此其他功能

Public Function SqlStr(ByVal s As String) As String
'Input: s=""      Returns: NULL
'Input: s="abc"   Returns: 'abc'
'Input: s="x'y"   Returns: 'x''y'

    If s = "" Then
        SqlStr = "NULL"
    Else
        SqlStr = "'" & Replace(s, "'", "''") & "'"
    End If
End Function

您可以使用来检查密码

If DCount("*", "tblEmployees", _
    "strEmpName = " & SqlStr(LoginName()) & " AND strPwd = " & SqlStr(txtPassword)) = 1 Then
    ...
Else
    ...
End If

顺便说一句,如果此代码位于表的accdb中或这些表链接到的accdb中,则无需创建连接和使用ADODB。只需将此查询SELECT strEmpName FROM tblEmployees ORDER BY strEmpName放在ComboBox的Row Source属性中即可。

注意:这是Access VBA代码。


更新

从您新发布的代码中,我看到您正在将一个员工ID与一个员工姓名([lngEmpID]=" & Me.cboUsername.Value)进行比较,这当然是行不通的。

确保组合框的Row Source TypeTable/Query。将此代码放在ComboBox的Row Source属性中。

SELECT lngEmpID, strEmpName FROM tblEmployees ORDER BY strEmpName

与您的代码相比,它添加了ID。将Column Count设置为2,将Column Widths设置为0cm。这将隐藏ComboBox中的Id列。现在,组合框的值是ID而不是名称。