CreateDatabase Delphi VCL

Posted on

Question :

How to create the database automatically if it does not exist, same in the app of Delphi Android, but I want to do with Delphi VCL. I want my first run application to automatically create the database where I’m going to run scripts to generate the tables.

I’m trying following code:

if NOT FileExists(Trim(sPath)) then
  conn.Params.Values['CreateDatabase']  := 'True'
  conn.Params.Values['CreateDataBase']  := 'False';

I’m using Delphi XE10 with Firebird and connected with FDConnection .


Answer :

While doing this in Delphi (trial and error) and Google I managed to solve, in addition to assigning ‘True’ to the CreateDatabase also assign the other params, yes it worked,

    procedure Tdm.connBeforeConnect(Sender: TObject);
    var sPath: string;
       sPath := gsAppPath +'DBMeuDB.fdb' ;
       FDConnection1.Params.Values['CreateDatabase'] := BoolToStr(not FileExists(Trim(sPath)),True);
       FDConnection1.Params.Values['Database']     := Trim(sPath);
       FDConnection1.Params.Values['DriverID']     := 'FB';
       FDConnection1.Params.Values['User_Name']    := 'SYSDBA';
       FDConnection1.Params.Values['Password']     := 'masterkey';
       FDConnection1.Params.Values['CharacterSet'] := 'WIN1252';
       FDConnection1.Params.Values['Dialect']      := '3';

Thanks to everyone.


To complement the above answer
Puts a component of TFDQuery

FDQueryclose.sql.add (' create table teste('                ); 
FDQueryclose.sql.add ('    n_fields1    integer default 0, '); 
FDQueryclose.sql.add ('    n_fields2    integer default 0, '); 
FDQueryclose.sql.add ('    n_fields3    varchar(50))       '); 

So you create the tables.


Leave a Reply

Your email address will not be published. Required fields are marked *