Search code examples
c++builderfiredac

How to query a TFDMemTable


I am trying to create a simple loop to process a TFDMemTable. I've dropped a TFDMemTable, a TFDQuery, and a TFDConnection on a Form, and I think I have wired everything up correctly, but when I activate the query it gives back an error message that there is no such table as FDMemTable1.

Here is demo code of what I am trying:

#include <vcl.h>
#pragma hdrstop
#include "Unit2.h"
#include "FireDac.Stan.Def.hpp"
//---------------------------------------------------------------------------
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
void __fastcall TForm2::FormCreate(TObject *Sender)
{
    FDMemTable1->InsertRecord(ARRAYOFCONST((L"Vic", 100, 30)));
    FDMemTable1->InsertRecord(ARRAYOFCONST((L"Jeong", 20, 20)));
    FDMemTable1->InsertRecord(ARRAYOFCONST((L"Christina", 400, 50)));
    FDMemTable1->InsertRecord(ARRAYOFCONST((L"Justina", 0, 60)));

    FDConnection1->ConnectionName = L"FDMemTable1";
    FDConnection1->DriverName = L"SQLite";
    FDConnection1->Connected = true;
    FDQuery1->Connection = FDConnection1;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
    UnicodeString x;
    FDQuery1->SQL->Text = "SELECT * FROM FDMemTable1";
    FDQuery1->Active = true;

    if (!FDQuery1->Eof) {
        x = FDQuery1->FieldByName(L"FullName")->AsString;
        
        ...

        FDQuery1->Next();
    }
}

How does one go about querying an existing TFDMemTable?


Solution

  • To query an FDMemTable you can use FireDAC's LocalSQL facility. Adding a TFDLocaSQL component to your form enables you to register one or more TDataSet-descendant dataset (using the Add method of its Datasets property), such as your FDMemTable, to be the target of a SQL search using Sqlite's SQL implementation. It should be more than adequate to execute your query and is very easy to use, once you've set it up.

    See https://docwiki.embarcadero.com/RADStudio/Sydney/en/Local_SQL_(FireDAC) for more information.

    This is the code from an answer of mine which uses FireDAC's localSQL with an FDMemTable. The code is written in Dellphi but should be trivial to translate into c++:

      FDConnection1.DriverName := 'SQLite';
      FDConnection1.Connected := True;
    
      FDLocalSQL1.Connection := FDConnection1;
      FDLocalSQL1.DataSets.Add(FDMemTable1);
    
      FDLocalSQL1.Active := True;
    
      FDQuery1.SQL.Text := 'select * from FDMemTable1 order by ID limit 5';
      FDQuery1.Active := True;