Android:使用AUTOINCREMENT列插入sqlite记录

时间:2011-11-09 19:12:41

标签: android 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 列?

更新/修复了上面两行(删除了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)";

1 个答案:

答案 0 :(得分:30)

从架构中删除NOT NULL,你就是黄金。

澄清: 在自动增量列上指定NOT NULL会使自动增量不起作用。 NOT NULL就是这样做的,所以你必须指定_id。

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