vendredi 18 septembre 2015

Delphi SQLite insert into a table with primary key as Autoincrement

I am trying to migrate my app from mySQL to SQLite, and in order to do that I recreated all my mySQL tables in SQLite.

I read about the fact that AUTOINCREMENT is not recommended to be used in declaring the actual autoincrement field. And instead of that I should just declare my autoincrement field as PRIMARY KEY NOT NULL, and SQLite would autoincrement it. All is fine except it does not work or I can't use it.

I use Delphi XE with Zeos and SQLite-3

Here is what I tried:

1.

  dm.ZConnection1.Protocol := 'sqlite-3';
  dm.ZConnection1.Database := 'myDB.s3db';
  dm.ZConnection1.Connect;
  dm.ZConnection1.ExecuteDirect('CREATE TABLE IF NOT EXISTS test ('+
  '  id int AUTOINC PRIMARY KEY,'+
  '  myval varchar(200) default NULL);');

  dm.ZConnection1.ExecuteDirect('insert into test (myval) values (''first'')');
  dm.ZConnection1.ExecuteDirect('insert into test (myval) values (''second'')');
  dm.ZConnection1.ExecuteDirect('insert into test (myval) values (''third'')');
  dm.ZConnection1.ExecuteDirect('insert into test (myval) values (''fourth'')');

If I run the above code, my table gets generated, but inserted rows have no values (NULLs I guess) in the ID field

  1. and then I tried replacing AUTOINC with AUTOINCREMENT and I get a syntax error while creating the table near AUTOINCREMENT, so I assume ZEOS does not support declaration of AUTOINCREMENT ?!?!

  2. And then I tried without AUTOINC, I just declared the ID field as

    id int(11) PRIMARY KEY,

and my code does not give me errors except the values of ID field are all empty (no autincrementation was done)

  1. If I add NOT NULL after PRIMARY KEY, then my code gives me errors because I am trying to insert null values in a NOT NULL field

So please let me know what exactly can I do to achieve what I need without having to manually calculate my next id value on each insert. Is it even possible?

Aucun commentaire:

Enregistrer un commentaire