Created
June 6, 2011 17:51
-
-
Save tebeka/1010709 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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