【问题标题】:Android: inserting sqlite record with AUTOINCREMENT columnAndroid:使用 AUTOINCREMENT 列插入 sqlite 记录
【发布时间】: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)";

【问题讨论】:

  • 你真的应该考虑使用SQLiteDatabase insert 方法而不是创建这些原始字符串语句
  • 同意。这是笨拙的代码,但是情况不允许使用替代方法。此外,应预先警告关注此线程的任何人,如上所示,SQL 插入语句中未经处理/未转义的用户输入是导致严重“eek”的原因。

标签: android sqlite


【解决方案1】:

从架构中删除 NOT NULL 并且你是金子。

澄清: 在自动增量列上指定 NOT NULL 会使自动增量不起作用。 NOT NULL 是导致它的原因,因此您必须指定 _id。

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

【讨论】:

  • 非常感谢,我遇到了类似的问题,您的解决方案帮助我继续前进。但是,我必须承认,在这种情况下删除 NOT NULL 是令人惊讶的不明显。
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 2012-06-03
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2021-06-12
相关资源
最近更新 更多