如果MS Access(数据库)中存在记录,如何通过Delphi检查?

时间:2013-09-29 12:47:02

标签: delphi login-system

您好我有一个Delphi 7项目任务,我们需要包含一个登录系统。我有一个注册页面,其中数据转到Access中的表。现在,当用户需要登录时,需要检查他/她的信息是否存在,然后他将被授予进一步的权限,但不知道如何执行此操作。

1 个答案:

答案 0 :(得分:1)

自从我升级到2005年以来已经有一段时间了,所以我无法为Delphi 7测试它,但是在Delphi 2005中,至少可以使用以下过程:

USES {$IFDEF UseParmsEvenThoughTheyAreNotNecessary } DB {$ELSE } StrUtils {$ENDIF } ,ADODB;

FUNCTION CanLogIn(CONST UserName,Password : STRING ; CONST AccessDatabaseFile,TableName,UserField,PasswordField : STRING) : BOOLEAN;
  VAR
    Connection : TADOConnection;
    DataSet    : TADODataSet;

  FUNCTION AccessConnStr(CONST FileName : STRING) : STRING;
    BEGIN
      {$IFDEF CPUX64 }
        Result:='Provider=Microsoft.ACE.OLEDB.12.0;Data source='+FileName
      {$ELSE }
        Result:='Provider=Microsoft.Jet.OLEDB.4.0.0;Data Source='+FileName
      {$ENDIF }
    END;

  {$IFNDEF UseParmsEvenThoughTheyAreNotNecessary }
    FUNCTION QuotedStr(CONST STR : STRING) : STRING;
      BEGIN
        Result:=''''+ReplaceStr(STR,'''','''''')+''''
      END;
  {$ENDIF }

  BEGIN
    Connection:=TADOConnection.Create(NIL);
    TRY
      Connection.ConnectionString:=AccessConnStr(AccessDatabaseFile);
      TRY
        Connection.Connected:=TRUE;
        TRY
          DataSet:=TADODataSet.Create(NIL);
          TRY
            DataSet.CommandType:=cmdText;
            {$IFDEF UseParmsEvenThoughTheyAreNotNecessary }
              DataSet.ParamCheck:=TRUE;
              DataSet.Parameters.CreateParameter('UserName',ftString,pdInput,80,UserName);
              DataSet.Parameters.CreateParameter('Password',ftString,pdInput,80,Password);
              DataSet.CommandText:='SELECT * FROM ['+TableName+'] WHERE ['+UserField+']=:UserName AND ['+PasswordField+']=:Password';
            {$ELSE }
              DataSet.ParamCheck:=FALSE;
              DataSet.CommandText:='SELECT * FROM ['+TableName+'] WHERE ['+UserField+']='+QuotedStr(UserName)+' AND ['+PasswordField+']='+QuotedStr(Password);
            {$ENDIF }
            TRY
              DataSet.Open;
              TRY
                Result:=NOT DataSet.EOF
              FINALLY
                DataSet.Close
              END
            EXCEPT
              Result:=FALSE
            END
          FINALLY
            DataSet.Free
          END
        FINALLY
          Connection.Close
        END
      EXCEPT
        Result:=FALSE
      END
    FINALLY
      Connection.Free
    END
  END;

参数:

UserName = Name of the user attempting to log in
Password = Password of the user
AccessDatabaseFile = The access database file
TableName = The name of the table containing the UserName/Password for allowed users
UserField = The name of the field in the above table that contains the user name
PasswordField = The name of the field in the above table that contains the password for the user

如果发生异常(找不到文件,错误的表名/字段名称或者你有什么),函数会捕获这些异常并返回FALSE。只有当整个函数成功并且在表中找到具有正确密码的用户时,该函数才会返回TRUE。