Binary Lion Studios

I code for fun and for food.

Create table if it doesn't exist

An easy way to create a table (and seed some data) if it doesn’t exist using Python and sqlite3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sqlite3

def main():
    conn = sqlite3.connect('data.db')
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()
    try:
        cursor.execute('select * from prefs')
    except sqlite3.OperationalError:
        print 'Table does not exist. Creating...'
        cursor.execute('create table prefs (key text, value text)')
        cursor.execute('insert into prefs(key, value) values (?, ?)', ('testing', '123'))
        conn.commit()
        print 'Finished creating table.'
    cursor.execute("select value from prefs where key = 'testing'")
    row = cursor.fetchone()
    print row['value'] # prints '123'