Skip to content

Instantly share code, notes, and snippets.

@tebeka
Created June 6, 2011 17:51
Show Gist options
  • Select an option

  • Save tebeka/1010709 to your computer and use it in GitHub Desktop.

Select an option

Save tebeka/1010709 to your computer and use it in GitHub Desktop.
import sqlite3
UPDATE_SQL = '''
UPDATE phonebook
SET phone = ?
WHERE name = ?
'''
INSERT_SQL = '''
INSERT INTO phonebook
VALUES (?, ?)
'''
def upsert(cursor, name, phone):
'''Update or insert phone for name'''
cursor.execute(UPDATE_SQL, (phone, name))
if cursor.rowcount > 0:
return
cursor.execute(INSERT_SQL, (name, phone))
def main():
schema = '''
CREATE TABLE phonebook (
name TEXT PRIMARY KEY,
phone TEXT
);
'''
db = sqlite3.connect(":memory:")
cur = db.cursor()
cur.executescript(schema)
upsert(cur, "daffy", "555-555-5555")
upsert(cur, "daffy", "555-555-5556")
cur.execute("SELECT phone FROM phonebook WHERE name=?", ("daffy",))
print(cur.fetchone()[0])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment