在数据库中创建 android SQLite table 时出现语法错误

Syntax error on creating android SQLite table in database

我根据以下需求创建了一个table:

  1. 稍后在我的代码中使用游标,所以我在 table

  2. 中创建了一个列 _ID
  3. 因为我只想使用自己的主键,所以我将列 'barcode' 设置为唯一的主键。

所以 table 如下所示:

CREATE TABLE product (
_id INTEGER,
barcode TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
categoryid INTEGER NOT NULL,
FOREIGN KEY (categoryid) REFERENCES category (_id) ON DELETE CASCADE)

以上 table 已正确创建,但我需要 _id 列自动递增,因此我修改 table 如下:

CREATE TABLE product (
_id INTEGER AUTOINCREMENT NOT NULL,
barcode TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
categoryid INTEGER NOT NULL,
FOREIGN KEY (categoryid) REFERENCES category (_id) ON DELETE CASCADE)

调试我的应用程序时,出现以下错误:

near "AUTOINCREMENT": syntax error (code 1): , while compiling: 
CREATE TABLE product (_id INTEGER AUTOINCREMENT NOT NULL,barcode TEXT PRIMARY KEY NOT NULL,title TEXT NOT NULL,categoryid INTEGER NOT NULL, FOREIGN KEY (categoryid) REFERENCES category (_id) ON DELETE CASCADE)

我需要 barcode 列作为唯一的主键,但 _ID 列同时自增。

我可以使用由 _ID 和条形码组成的复合主键,这样 _ID 可以毫无问题地设置为自动递增,但这样做可以插入多个具有相同条形码(具有不同 _ID)的产品,而我希望条码在整个table.

中是唯一的

那么如何摆脱它呢?

来自 link:https://www.sqlite.org/autoinc.html, auto increment cannot be set to non primary field, so I think you can try the follow solution, it might help: SQLite auto-increment non-primary key field

这种情况能不能不用ROWID?它可以满足您的所有要求,并且内置于大多数 sqlite 表中。 在您的查询中只需执行 select X, Y, ROWID from Z.