Android:插入AUTOINCREMENT列的sqlite记录



我在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);

我可以插入一个记录到这个表的唯一方法是通过指定一个值_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);

如果我离开_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)

我如何安排查询(或模式),使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)";

从schema中去掉NOT NULL,你就成功了。

澄清:在自动增量列上指定NOT NULL将使自动增量不起作用。NOT NULL是什么,所以你必须指定_id。

一旦你删除了它,并且在插入语句中不包含_id, SQL将接收_id为NULL并自动处理为你设置_id。

最新更新