[fpc-pascal] Database access in console program

Koenraad Lelong fpascal at brouwerij.homelinux.net
Wed Nov 9 17:49:48 CET 2011


Hi,

I don't know if it's the right place to ask, maybe it's for the lazarus 
list.

Anyway, I'm trying to make a console-application that writes data to a 
Firebird database. With Lazarus I created a console application.
I seem to be able to connect and open the table, but I can't insert data.
Are there examples anywhere ? I know how to do this in a graphical 
environment, but I need the console app, it will run on a non-gui server.

Here is my code that goes in the application on-create method :

   MyDB:=TIBConnection.Create(nil);
   MyDB.Hostname:='server';
   MyDB.DatabaseName:='/data/firebird/database.fdb';
   MyDB.Transaction:=DupFilesTransaction;
   MyDB.UserName:='user';
   MyDB.Password:='password';
   try
    MyDB.Open;
    writeln('DB open');
   except
    on E: Exception do
     begin
      writeln(E.Message);
     end;
   end;
   myTransaction:=TSQLTransaction.Create(nil);
   myTransaction.Database:=MyDB;
   try
    myTransaction.StartTransaction;
    writeln('Transaction open');
   except
    on E: Exception do
     begin
      writeln(E.Message);
     end;
   end;
   myTable:=TSQLQuery.Create(nil);
   myTable.Database:=MyDB;
   myTable.Transaction:=myTransaction;

   myTable.SQL.Clear;
   myTable.SQL.Add('select * from myTable');
   myTable.InsertSQL.Clear;
   myTable.InsertSQL.Add('INSERT INTO myTable(');
   myTable.InsertSQL.Add(      'Field1,');
   myTable.InsertSQL.Add(      'Field2');
   myTable.InsertSQL.Add(      ')');
   myTable.InsertSQL.Add(      'VALUES(');
   myTable.InsertSQL.Add(      ':Field1,');
   myTable.InsertSQL.Add(      ':Field2');
   myTable.InsertSQL.Add(      ')');
   try
    myTable.Open;
    writeln('Table open');
   except
    on E: Exception do
     begin
      writeln(E.Message);
     end;
   end;


When I insert values I do :

   myTable.Params.ParamByName('Field1').Value:='Value1';
   myTable.Params.ParamByName('Field2').Value:='Value2';
   try
   myTable.ApplyUpdates;
   except
    on E: Exception do
     writeln(E.Message)
   end;

If I try this I get an error stating parameter Field1 does not exist.

Any references ?

Thanks,

Koenraad Lelong.





More information about the fpc-pascal mailing list