Roshan Book

My Tech Notebook

Python tutorial 17–Objects in database


import sqlite3

class database:
    def __init__(self, **kwargs):
        self.filename = kwargs.get(‘filename’)
        self.table = kwargs.get(‘table’, ‘test’)
   
    def sql_do(self, sql, *params):
        self._db.execute(sql, params)
        self._db.commit()
   
    def insert(self, row):
        self._db.execute(‘insert into {} (t1, i1) values (?, ?)’.format(self._table), (row[‘t1’], row[‘i1’]))
        self._db.commit()
   
    def retrieve(self, key):
        cursor = self._db.execute(‘select * from {} where t1 = ?’.format(self._table), (key,))
        return dict(cursor.fetchone())
   
    def update(self, row):
        self._db.execute(
            ‘update {} set i1 = ? where t1 = ?’.format(self._table),
            (row[‘i1’], row[‘t1’]))
        self._db.commit()
   
    def delete(self, key):
        self._db.execute(‘delete from {} where t1 = ?’.format(self._table), (key,))
        self._db.commit()

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

    def __iter__(self):
        cursor = self._db.execute(‘select * from {} order by t1’.format(self._table))
        for row in cursor:
            yield dict(row)

    @property
    def filename(self): return self._filename

    @filename.setter
    def filename(self, fn):
        self._filename = fn
        self._db = sqlite3.connect(fn)
        self._db.row_factory = sqlite3.Row

    @filename.deleter
    def filename(self): self.close()

    @property
    def table(self): return self._table
    @table.setter
    def table(self, t): self._table = t
    @table.deleter
    def table(self): self._table = ‘test’

    def close(self):
            self._db.close()
            del self._filename

def main():
    db = database(filename = ‘test.db’, table = ‘test’)

    print(‘Create table test’)
    db.sql_do(‘drop table if exists test’)
    db.sql_do(‘create table test ( t1 text, i1 int )’)

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

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

    print(‘Update rows’)
    db.update(dict(t1 = ‘one’, i1 = 101))
    db.update(dict(t1 = ‘three’, i1 = 103))
    for row in db: print(row)

    print(‘Delete rows’)
    db.delete(‘one’)
    db.delete(‘three’)
    for row in db: print(row)

if __name__ == “__main__”: main()

Advertisements

4 responses to “Python tutorial 17–Objects in database

  1. Louis Vuitton Handbags For Sale December 5, 2011 at 5:14 am

    Astonishingly illuminating many thanks, There’s no doubt that your trusty visitors will likely want a whole lot more articles along these lines keep up the wonderful effort.

  2. Louis Vuitton Knockoffs Handbags December 5, 2011 at 5:20 pm

    I definitely delight in visiting your web-site! your great method to see points is what keeps me interested. Thanks so significantly!!!!

  3. LV Handbags Sale December 6, 2011 at 5:47 am

    Hey there dude, This was a decent page for such adifficult area to speak about.

  4. cheap Moncler December 14, 2011 at 1:58 am

    This page is the start I have discovered that’s not rubbish. It’s going to take a first-class work ethic to put out something decent significantly site, continue the good work.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: