Dev HelpersOpen library
← Back

Update an existing SQLite row with an upsert

Update an existing SQLite row with an upsert in Python.

Open this example in the interactive library

Source code

from contextlib import closing
import sqlite3
with closing(sqlite3.connect(':memory:')) as db:
    db.execute('CREATE TABLE scores (name TEXT PRIMARY KEY, score INTEGER)')
    sql = 'INSERT INTO scores VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET score=excluded.score'
    db.executemany(sql, [('Ada', 7), ('Ada', 9)])
    print(db.execute('SELECT * FROM scores').fetchall())

Sample output

[('Ada', 9)]