Sqlite3 INSERT 语句中的 Python 变量替换 [英] Python variable replacement in Sqlite3 INSERT statement
问题描述
在更新针对已知 rowid 的 Sqlite 数据时,有没有办法使用 Python 的变量替换?我想说的是:
Is there a way to use Python's variable replacement when updating Sqlite data targeting a known rowid? I am trying to say something like:
cursor.execute('INSERT INTO Words(rowid,f1,f2) VALUES(?,?,?)', [rowid,2,3])
问题是这失败并出现错误:
The problem is that this fails with error:
sqlite3.IntegrityError: PRIMARY KEY must be unique
我想在不更改 rowid 编号的情况下将值列表写入表的现有记录中.从值列表更新所有字段的可接受方法是什么?
I want to write a list of values into the table's existing record without changing the rowid number. What's the accepted way to update all fields from a list of values?
推荐答案
您使用 UPDATE
而不是 INSERT
:
cursor.execute('UPDATE Words SET f1=?, f2=? WHERE rowid=?', [2, 3, rowid])
这告诉数据库用新值更新 f1
和 f2
列,对于 rowid
与您指定的值匹配的所有行.
This tells the database to update the f1
and f2
columns with new values, for all rows where rowid
matches your specified value.
或者,使用INSERT OR REPLACE
语法;如果违反了唯一性约束(例如主键不是唯一的),则会发出 UPDATE
代替,但如果 rowid
尚不存在,则将插入新行:
Alternatively, use the INSERT OR REPLACE
syntax; if a uniqueness constraint (such as the primary key not being unique) is violated, an UPDATE
is issued instead, but if rowid
is not yet present a new row will be inserted:
cursor.execute('INSERT OR REPLACE INTO Words(rowid,f1,f2) VALUES(?,?,?)', [rowid,2,3])
这篇关于Sqlite3 INSERT 语句中的 Python 变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!