如何在每次有人登录我的数据库时进行临时查询?

问题描述:

我想这样做,所以每次学生登录到这个数据库时,它会创建一个查询来显示他们的成绩,通过DLookup和QueryDef来匹配LoginTable中的FullName和StudentGrades表中的FullName(我的想法很少关于如何使用,所以我可能完全错误)。如果你知道如何解决这个问题,请解释QueryDef,或者知道一个更简单的方法来做到这一点,请帮助我,谢谢。如何在每次有人登录我的数据库时进行临时查询?

为登录按钮VBA代码:

Private Sub Command1_Click() 
'If there is no password or username then shows pop-up 
'usertext is username box and passtext is password box 
If IsNull(Me.usertext) Then 
    MsgBox "Please enter login", vbInformation, "LOGIN REQUIRED" 
    Me.usertext.SetFocus 
ElseIf IsNull(Me.passtext) Then 
    MsgBox "Please enter password", vbInformation, "PASSWORD REQUIRED" 
    Me.passtext.SetFocus 
'Sets actual values from table to values started above and checks if username and password actually match up with table 
Else 
    If (IsNull(DLookup("[UserLogin]", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "' and password = '" & Me.passtext.Value & "'"))) Then 
    MsgBox "Username/password not valid" 
'Checks for what securitylvl is the login and sets up studentqry if user is student 
Else 
    Dim SecurityLvl As Variant 
    Dim StudentName As Variant 
    Dim StudentQry As QueryDef 
    SecurityLvl = DLookup("SecurityLvl", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "'") 
    StudentName = DLookup("FullName", "LoginTable", "[UserLogin] ='" & Me.usertext.Value & "'") 
    If (SecurityLvl = "Admin") Then 
    MsgBox "Admin Login successful" 
    DoCmd.Close 
    DoCmd.OpenForm "AdminForm" 
    ElseIf (SecurityLvl = "Professor") Then 
     MsgBox "Teacher Login successful" 
     DoCmd.Close 
     DoCmd.OpenForm "TeacherForm" 
      ElseIf (SecurityLvl = "Student") Then 
      MsgBox "Student Login successful" 
      DoCmd.Close 
      Set StudentQry = DBVeryinitialprototype.CreateQueryDef("StudentQuery", "Select * from StudentGrades where `FullName` = StudentName") 
      DoCmd.OpenQuery "StudentQuery" 
      End If 
       End If 
        End If 
         End 
End Sub 
+0

上述代码不起作用?为什么是一个临时查询?你在哪里使用它?只需运行一个通用查询即可在* LoginTable *中过滤给学生。 – Parfait

+0

我在StudentQry上遇到了424对象错误。如何进行永久性查询并使其显示在导航的访问查询中?我只是查了一下如何使用VBA进行查询,并开始了我所看到的第一件事。我甚至不知道我为什么放置临时查询,我可能刚刚删除它在一个新的登录。 –

没有必要对于临时查询被创建/与每个登录删除。只需创建一个在动态数据上运行的永久性查询。具体而言,加入StudentGradesLoginTable其中输出将是当前登录的用户。

由于您的登录过程不清楚,可能您有一个状态字段,用于标识当前会话中的哪个学生(除非您每次清除登录表中的所有记录)。

SELECT s.* 
FROM StudentGrades s 
INNER JOIN LoginTable l 
    ON l.FullName = s.StudentName 
WHERE l.LoginStatus = True 

理想情况下,你加入的标识,而不是完整的字符串值。登录应该有一个组合框,允许选择带有隐藏绑定字段的学生作为ID,或者在键入的文本框字段中检索相应的StudentID。这样,StudentQuery行文:

SELECT s.* 
FROM StudentGrades s 
INNER JOIN LoginTable l 
    ON l.StudentID = s.StudentID 
WHERE l.LoginStatus = True 

如何创建一个永久查询?这应该已经在您的MS Access已经覆盖101路线:

  1. 创建色带上选项卡,在查询部分中,单击查询设计
  2. 使用设计视图创建包含表(选择表/连接/字段)或SQL视图的查询以使用SQL构建查询。
  3. 完成绘图后,单击保存。然后查询应该显示在导航窗格中。

当前,您将使用querydefs创建查询的编码路径。但是再次不需要动态地执行此操作,只需创建一次查询,并且数据应该相应地对齐。

+0

我正在为一个学校项目做这件事。如果起初我很困惑,我很抱歉。谢谢,我现在明白了。 –