【发布时间】:2011-11-09 19:12:40
【问题描述】:
我在 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)";
【问题讨论】:
-
你真的应该考虑使用
SQLiteDatabaseinsert方法而不是创建这些原始字符串语句 -
同意。这是笨拙的代码,但是情况不允许使用替代方法。此外,应预先警告关注此线程的任何人,如上所示,SQL 插入语句中未经处理/未转义的用户输入是导致严重“eek”的原因。