[DB-SIG] Python db programming conventions

Andy Dustman farcepest at gmail.com
Mon Nov 22 04:42:46 CET 2010


On Sun, Nov 21, 2010 at 3:02 PM, John Q. Public <sqlite3.user at gmail.com> wrote:
>
> Is this how my createdb() method should look like?
> How would you write this method so it is both readable and correct?
> Thank you for your time and patience.
>
> def createdb(self):
>    try:
>        con = sqlite3.connect(db)
>        cur = con.cursor()
>
>        cur.execute('''
>            CREATE TABLE t1
>            (
>                kid INTEGER PRIMARY KEY,
>                c1 TEXT,
>                c2 TEXT
>            )
>        ''')
>
>        cur.execute('''
>            CREATE TABLE t2
>            (
>                kid INTEGER PRIMARY KEY,
>                c1 TEXT,
>                c2 TEXT
>            )
>        ''')
>
>        cur.execute('''
>            CREATE TABLE t3
>            (
>                kid INTEGER PRIMARY KEY,
>                c1 TEXT,
>                c2 TEXT
>            )
>        ''')
>
>        con.commit()
>    except:
>        a = "ERROR: createdb did not commit. \n"
>        b = "tried this sql:   \n"
>        raise IOError, "%s%s%s" % ( a, b, sql )
>    finally:
>        cur.close()
>        con.close()

You never actually set sql anywhere, so you'll always get a NameError
instead of IOError. It would probably be better to not catch the
exception at all in this function.
-- 
Question the answers


More information about the DB-SIG mailing list