我如何在 sqlite 数据库 Python 中创建一个包含列索引的新列?

How would I create a new column containing an index of column in sqlite database Python?

假设我有一个 table,其中有一列名为名称,每一行都有一个观察值。

 NAME
('John Smith')
('Paul Smith')
('Jake Smith')

我将如何修改 table 以便它包含每一行的索引以获得如下所示的内容。我只需要使用标准 Python 包。

 NAME               INDEX
('John Smith')        1
('Paul Smith')        2
('Jake Smith')        3



con = sqlite3.connect('example.db')
cur = con.cursor()
table= "CREATE TABLE names(name TEXT)"
cur.execute(table)

INSERT INTO names(name)
VALUES ('John Smith');
VALUES ('Paul Smith');
VALUES ('Jake Smith');

SQLite 会自动创建一个名为“ROWID”的隐藏列。

sqlite> create table names(id TEXT);
sqlite> insert into names values ('John Smith'),('Paul Smith'),('Jake Smith');
sqlite> select rowid, id from names;
1|John Smith
2|Paul Smith
3|Jake Smith
sqlite> ALTER TABLE names ADD COLUMN names_index INTEGER;
sqlite> UPDATE names SET names_index=rowid;
sqlite> .mode box
sqlite> SELECT * FROM names;
┌────────────┬─────────────┐
│     id     │ names_index │
├────────────┼─────────────┤
│ John Smith │ 1           │
│ Paul Smith │ 2           │
│ Jake Smith │ 3           │
└────────────┴─────────────┘
sqlite>

如果您创建自己的列 INTEGER PRIMARY KEY,它将用作 ROWID。