FireDAC is universal data access library which provides a common API to connect with different database back-end , maintaining the access to database specific features and without compromising on performance. FireDAC enables native high-speed access to almost all enterprise database including no SQL databases such as MongoDB
In this article we will connect MS SQL Server database with Delphi using FireDAC. We will go through code to make database connection.
Start a new Delphi application
Go to Delphi IDE and select File -> New -> VCL Form application - Delphi
Add a TButton to Delphi Form
Add FireDAC component to private section of the class
- TFDPhysMSSQLDriverLink
- TFDConnection
- TFDQuery
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
FireDAC.Phys.MSSQLDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, Vcl.StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
private
{ Private declarations }
FDBConnection: TFDConnection;
FMSSQLDriverLink: TFDPhysMSSQLDriverLink;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
end.
Note the units added to uses clause related to components used in the application.
Add the below code to button click event
procedure TForm2.Button1Click(Sender: TObject);
begin
try
FMSSQLDriverLink := TFDPhysMSSQLDriverLink.Create(nil);
FDBConnection := TFDConnection.Create(nil);
FDBConnection.Params.DriverID := 'MSSQL';
FDBConnection.Params.UserName := 'sa';
FDBConnection.Params.Password := '<your_password>';
FDBConnection.Params.Database := '<your_database>';
FDBConnection.Params.Add('server=<your_DB_server>');
FDBConnection.Connected := True;
if FDBConnection.Connected then begin
ShowMessage('Connected successfully');
end;
finally
if FDBConnection.Connected then begin
FDBConnection.Close;
end;
end;
end;
This is very basic steps to connect with SQL server using FireDAC, let me know your thoughts in comment.
I have prepared a YouTube video to show a demo of Delphi - MSSQL connection Connect Delphi with MSSQL database using FireDAC