0

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

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?

1 Answer 1

3

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.