Android:使用AUTOINCREMENT列插入sqlite记录

wuf*_*foo 13 sqlite android

我在android上创建了一个sqlite数据库,如下所示:

sqlite> .schema
CREATE TABLE criterion ('_id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, active text, important text, sort int, summary text, user text, category_id int, entrytype int);
Run Code Online (Sandbox Code Playgroud)

我可以在此表中插入记录的唯一方法是为_id指定一个我想要自动递增的值.这是我可以使插入工作的唯一方法:

recid = totalrecs + 1;
String q = "insert into criterion (_id, active, important, sort, summary, user, category_id, entrytype) values (" + recid + ", \"1\", \"0\", 99, \"foobar\", \"1\", 99, 0)";
Log.d (TAG, "query:" + q);
mDb.execSQL (q);
Run Code Online (Sandbox Code Playgroud)

如果我退出_id列并且没有为_id指定值,我会收到错误:

android.database.sqlite.SQLiteConstraintException: criterion._id may not be NULL: insert into criterion(active, important, sort, summary, user, category_id, entrytype) values ("1", "0", 99, "foobar", "1", 99, 0)
Run Code Online (Sandbox Code Playgroud)

如何安排查询(或架构),以便Android负责增加_id列?

更新/修复上面的2行(删除NOT NULL,从查询中删除_id):

CREATE TABLE criterion ('_id' INTEGER PRIMARY KEY AUTOINCREMENT, active text, important text, sort int, summary text, user text, category_id int, entrytype int);

String q = "insert into criterion (active, important, sort, summary, user, category_id, entrytype) values (\"1\", \"0\", 99, \"foobar\", \"1\", 99, 0)";
Run Code Online (Sandbox Code Playgroud)

Gee*_*man 31

从架构中删除NOT NULL,你就是金色的.

澄清:在自动增量列上指定NOT NULL使得自动增量不起作用.NOT NULL正在制作它所以你必须指定_id.

一旦删除它,并且在insert语句中不包含_id,SQL将收到_id为NULL并自动处理为您设置_id.