在SQLite数据库中的特定位置插入一行

Viv*_*rde 4 sql sqlite insert-update sql-update android-sqlite

我在SQLite Manager中创建了数据库,但是我忘了提到一行.

现在,我想手动在中间添加一行,在其下方,其余的自动增量键应自动增加1.我希望我的问题很清楚.

谢谢.

Ola*_*che 6

您不应该关心键值,只需在最后添加行.

如果你真的需要这样做,你可能只需用这样的东西来更新密钥.如果要在键87处插入新行

为钥匙腾出空间

update mytable
set key = key + 1
where key >= 87
Run Code Online (Sandbox Code Playgroud)

插入你的行

insert into mytable ...
Run Code Online (Sandbox Code Playgroud)

最后更新新行的密钥

update mytable
set key = 87
where key = NEW_ROW_KEY
Run Code Online (Sandbox Code Playgroud)


Mar*_*oni 5

我只会更新 ID,增加它们,然后手动插入记录设置 ID:

CREATE TABLE cats (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name VARCHAR
);
INSERT INTO cats (name) VALUES ('John');
INSERT INTO cats (name) VALUES ('Mark');
SELECT * FROM cats;

| 1 | John |
| 2 | Mark |

UPDATE cats SET ID = ID + 1 WHERE ID >= 2; -- "2" is the ID of forgotten record.
SELECT * FROM cats;

| 1 | John |
| 3 | Mark |

INSERT INTO cats (id, name) VALUES (2, 'SlowCat'); -- "2" is the ID of forgotten record.
SELECT * FROM cats;

| 1 | John    |
| 2 | SlowCat |
| 3 | Mark    |
Run Code Online (Sandbox Code Playgroud)

使用 AUTOINCREMENT 功能插入的下一条记录将具有倒数第二个 ID(在我们的例子中为 4)。