Skip to content Skip to sidebar Skip to footer

Python Variable Replacement In Sqlite3 INSERT Statement

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

Solution 1:

You use UPDATE instead of INSERT:

cursor.execute('UPDATE Words SET f1=?, f2=? WHERE rowid=?', [2, 3, rowid])

This tells the database to update the f1 and f2 columns with new values, for all rows where rowid matches your specified value.

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])

Post a Comment for "Python Variable Replacement In Sqlite3 INSERT Statement"