Skip to content

Instantly share code, notes, and snippets.

@nsabine
Created May 6, 2013 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsabine/5527945 to your computer and use it in GitHub Desktop.
Save nsabine/5527945 to your computer and use it in GitHub Desktop.
Read and write simple data to a sqlite database
import sqlite3
db_filename = "test.db"
def create_schema(conn):
schema = """
drop table if exists word;
create table word (
id integer primary key autoincrement not null,
w text
);
"""
conn.executescript(schema)
def insert_data(data, conn):
conn.execute("insert into word (w) values (?);", (data,))
def read_data(conn):
data = []
cursor = conn.cursor()
cursor.execute("select id, w from word;")
for row in cursor.fetchall():
id, w = row
data.append((id, w))
return data
if __name__ == '__main__':
from random_generator import random_word
with sqlite3.connect(db_filename) as conn:
create_schema(conn)
for rw in random_word(5):
insert_data(rw, conn)
for t in read_data(conn):
print('%2d %s' % t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment