Created
May 6, 2013 20:31
-
-
Save nsabine/5527945 to your computer and use it in GitHub Desktop.
Read and write simple data to a sqlite database
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 | |
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