Last active
June 4, 2023 01:32
-
-
Save gka/5296492 to your computer and use it in GitHub Desktop.
The code below does the same as the example snippet you've just seen: opening a database connection,
creating a new table with some columns, storing some data, altering the table schema and adding another row.
This file contains 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 | |
# open connection and get a cursor | |
conn = sqlite3.connect(':memory:') | |
c = conn.cursor() | |
# create schema for a new table | |
c.execute('CREATE TABLE IF NOT EXISTS sometable (name, age INTEGER)') | |
conn.commit() | |
# insert a new row | |
c.execute('INSERT INTO sometable values (?, ?) ', ('John Doe', 37)) | |
conn.commit() | |
# extend schema during runtime | |
c.execute('ALTER TABLE sometable ADD COLUMN gender TEXT') | |
conn.commit() | |
# add another row | |
c.execute('INSERT INTO sometable values (?, ?, ?) ', ('Jane Doe', 34, 'female')) | |
conn.commit() | |
# get a single row | |
c.execute('SELECT name, age FROM sometable WHERE name = ?', ('John Doe', )) | |
row = list(c)[0] | |
john = dict(name=row[0], age=row[1]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And just to cross-link to those coming from google, this gist is linked to from http://dataset.readthedocs.org/en/latest/