Connect FDQuery to DBGrid programatically — Delphi

Soon Sam Santos
2 min readJan 1, 2019

After estabilishing a successfully connection to your database you may want to display your tables’ data into your delphi application using FireDac. To connect to MySQL you can check these articles: Connect MySQL to Delphi and Connect Interbase to Delphi.

In the left picture I have a database table being displayed in a DBGrid in my delphi application.

Step 1. Add the components

Add the following components to your project.

  1. TDBGrid (name: DBGrid1)
  2. TFDQuery (name: FDQuery1)
  3. TDataSource (name: DataSource1)

Step 2. Connect the components

Select the DBGrid1, in the Object Inspector look for DataSource property and add your DataSource1 to it.

Select the DataSource1, in the Object Inspector look for DataSet property and add your FDQuery1 to it.

Step 3. Add the code

In your FormCreate method add the following code.

procedure TForm1.FormCreate(Sender: TObject);
begin
with FDQuery1 do
begin
Connection := frmDM.FDConnection;
Active := False;
SQL.Clear;
Open('SELECT * FROM <table_name>');
end;
DataSource1.DataSet := FDQuery1;
end;

First, we connect the FDQuery to the FDConnection programatically, my FDConnection is located in my DataModule (frmDM) that is why I use the following line.

Connection := frmDM.FDConnection;

To do that you will need to add your DataModule to the uses clauses, you can do it by pressing Alt+F11, choosing your DataModule and confirming it.

Then we set the FDQuery Active to false and clean any SQL text that was previously on it. Note that in this case it would not be necessary to add these two lines, however, in a big application you may end up with a FDQuery with more SQL text than you need, so that’s why it is a good practice to clean it before using.

Finally, we open our FDQuery by selecting a table in our database.

Notice that in the end I connect the DataSource to the DataSet again (I connected it previously at design time). I do that for two reasons: First to show you guys how to do things at design time and programatically. Second, to make sure the connection was made.

Problems

After running your project you may end up with a ‘read out of address error’. You should know that the DataModule must be created before your Form. If you are in this situation check this answer on SO.

--

--

Soon Sam Santos

Flutter and Delphi Developer at Green. Teacher at SoonClass