[yunqa.de] Re: How to open SQLite database file regardless if the file exists or not

  • From: Delphi Inspiration <delphi@xxxxxxxx>
  • To: yunqa@xxxxxxxxxxxxx
  • Date: Mon, 07 Feb 2011 11:37:25 +0100

On 07.02.2011 10:20, Tobias Rapp wrote:

> When using the object-based interface of DISQLite (tDISQLiteDatabase
> class): How can I open a database file in a way that the file is
> created if it does not exist yet and opened if the file is already
> existing?
> 
> When I use Open() the call fails if the file is not existing yet, if
> I call CreateDatabase() the file is always deleted first if it
> exists.

Use exceptions, as shown in the DISQLite3_ClientDataSet_Grid demo.
Example code:

{ Open the database. }
DISQLite3Database.DatabaseName := 'Test.db3';
try
  DISQLite3Database.Open;
except
  on e: EFOpenError do
    begin
      { If database does not yet exist, create it now ... }
      DISQLite3Database.CreateDatabase;
      DISQLite3Database.Execute(
        'CREATE TABLE IF NOT EXISTS Products(' +
        '"ID" INTEGER PRIMARY KEY,' +
        '"Name" TEXT)');
    end;
else
  raise;
end;

If you do not want to initialize the database structure, you can
override the TDISQLite3Database.DoAfterCreateDatabase method and create
table / views / triggers there. This is shown in the
DISQLite3_Drive_Catalog demo, DISQLite3_Drive_Catalog_DB.pas.

> I could try to add a FileExists() in my code but this seems a bit
> unsafe as I want to open the database from multiple threads and thus
> a race-condition would occur.

I suggest to check from the main thread if the database file exists and
otherwise create it from right there, before you run any additional
threads.

Alternatively, thread synchronization can help against race conditions
but if more difficult to debug.

Ralf
_______________________________________________
Delphi Inspiration mailing list
yunqa@xxxxxxxxxxxxx
//www.freelists.org/list/yunqa



Other related posts: