PDA

View Full Version : Using auto_increment in QSql



SykeS
20th May 2010, 22:03
I have working database and I want to use auto_increment for id's in my tables.


query.exec("create table przedmioty(id int auto_increment not null primary key, nazwa varchar(40), skrot varchar(10))");
creates table, but:

query.exec("insert into przedmioty(skrot, nazwa) values('Matematyka', 'mat')");
throws QSqlError(19, "Unable to fetch row", "constraint failed") .

I want to mention that without "auto_increment" my program adds records.

What to do?

norobro
21st May 2010, 00:38
Assuming that you are still using SQLite, I found this (http://www.sqlite.org/faq.html#q1) by Googling "SQLite autoincrement".

ChrisW67
21st May 2010, 02:45
If it is SQLite (it looks like MySQL) then the syntax for the auto key is:

query.exec("create table przedmioty(id integer primary key, nazwa varchar(40), skrot varchar(10))");
or

query.exec("create table przedmioty(id integer primary key autoincrement, nazwa varchar(40), skrot varchar(10))"); SQLite is very particular about the form of the id column declaration.

This is what Sqlite makes of these options:

SQLite version 3.6.23.1
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table przedmioty(id int auto_increment not null primary key, nazwa varchar(40), skrot varchar(10));
sqlite> insert into przedmioty (skrot, nazwa) values ('test', 'test');
Error: przedmioty.id may not be NULL
sqlite> drop table przedmioty;

sqlite> create table przedmioty(id integer primary key, nazwa varchar(40), skrot varchar(10));
sqlite> insert into przedmioty (skrot, nazwa) values ('test', 'test');
sqlite> insert into przedmioty (skrot, nazwa) values ('test', 'test');
sqlite> select * from przedmioty;
1|test|test
2|test|test
sqlite> drop table przedmioty;

sqlite> create table przedmioty(id integer primary key autoincrement, nazwa varchar(40), skrot varchar(10));
sqlite> insert into przedmioty (skrot, nazwa) values ('test', 'test');
sqlite> insert into przedmioty (skrot, nazwa) values ('test', 'test');
sqlite> select * from przedmioty;
1|test|test
2|test|test
sqlite>

SykeS
21st May 2010, 07:13
Thanks ChrisW67. Your code helped me a lot. Before posting a topic I found "autoincrement" in SQLite documentation, but I didn't know that "autoincrement" must be inserted after "primary key", and this column must be "integer" (I used "int"). Now everything works fine.

See you.