Roshan Book

My Tech Notebook

Python tutorial 16–CRUD application

import sqlite3

def insert(db, row):
    db.execute(‘insert into test (t1, i1) values (?, ?)’, (row[‘t1’], row[‘i1’]))

def retrieve(db, t1):
    cursor = db.execute(‘select * from test where t1 = ?’, (t1,))
    return cursor.fetchone()

def update(db, row):
    db.execute(‘update test set i1 = ? where t1 = ?’, (row[‘i1’], row[‘t1’]))

def delete(db, t1):
    db.execute(‘delete from test where t1 = ?’, (t1,))

def disp_rows(db):
    cursor = db.execute(‘select * from test order by t1’)
    for row in cursor:
        print(‘  {}: {}’.format(row[‘t1’], row[‘i1’]))

def main():
    db = sqlite3.connect(‘test.db’)
    db.row_factory = sqlite3.Row
    print(‘Create table test’)
    db.execute(‘drop table if exists test’)
    db.execute(‘create table test ( t1 text, i1 int )’)

    print(‘Create rows’)
    insert(db, dict(t1 = ‘one’, i1 = 1))
    insert(db, dict(t1 = ‘two’, i1 = 2))
    insert(db, dict(t1 = ‘three’, i1 = 3))
    insert(db, dict(t1 = ‘four’, i1 = 4))

    print(‘Retrieve rows’)
    print(dict(retrieve(db, ‘one’)), dict(retrieve(db, ‘two’)))

    print(‘Update rows’)
    update(db, dict(t1 = ‘one’, i1 = 101))
    update(db, dict(t1 = ‘three’, i1 = 103))

    print(‘Delete rows’)
    delete(db, ‘one’)
    delete(db, ‘three’)

if __name__ == “__main__”: main()


One response to “Python tutorial 16–CRUD application

  1. ftndwkuyqrj November 3, 2011 at 10:55 am

    NoMZl7 gxyqucukzkeo, [url=]mrwfnbqvaagv[/url], [link=]rwfyrrsfydbs[/link],

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: