3.4.2. Connecting to the database

To connect to the database, it is necessary to change the Connected property of the TFDConnection component to True or call the Open method. You can use the Open method to pass the username and password as parameters.

A Little Modification

We will replace the standard database connection dialog box in our application and allow users to make three mistakes while entering the authentication information. After three failures, the application will be closed.

To implement it, we will write the following code in the OnCreate event handler of the main data module.

  1. // After three unsuccessful login attempts, we close the application.
  2. xLoginCount := 0;
  3. xLoginPromptDlg := TLoginPromptForm.Create(Self);
  4. while (xLoginCount < MAX_LOGIN_COUNT) and
  5. (not FDConnection.Connected) do
  6. begin
  7. try
  8. if xLoginPromptDlg.ShowModal = mrOK then
  9. FDConnection.Open(
  10. xLoginPromptDlg.UserName, xLoginPromptDlg.Password)
  11. else
  12. xLoginCount := MAX_LOGIN_COUNT;
  13. except
  14. on E: Exception do
  15. begin
  16. Inc(xLoginCount);
  17. Application.ShowException(E);
  18. end
  19. end;
  20. end;
  21. xLoginPromptDlg.Free;
  22. if not FDConnection.Connected then
  23. Halt;