<div class="gmail_quote">On Sun, Nov 21, 2010 at 8:42 PM, Andy Dustman <span dir="ltr"><<a href="mailto:farcepest@gmail.com" target="_blank">farcepest@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<div><div></div><div><br>
<br>
</div></div>You never actually set sql anywhere, so you'll always get a NameError<br>
instead of IOError. It would probably be better to not catch the<br>
exception at all in this function.<br>
<font color="#888888">--<br>
Question the answers<br>
</font><div><div></div><div>_______________________________________________<br></div></div></blockquote><div> <br>Thank you, Andy!<br><br>I missed that. That's why open source code is a good thing. More eyes looking finds problems.<br>
This time I actually entered the code into a file and executed it. A working version follows:<br><br><code><br>from __future__ import print_function<br>import sqlite3<br>import sys<br>def createdb(db):<br> try:<br>
con = sqlite3.connect(db)<br> cur = con.cursor()<br> sql = '''<br> CREATE TABLE t1<br> (<br> kid INTEGER PRIMARY KEY,<br> c1 TEXT,<br> c2 TEXT<br>
)'''<br> cur.execute(sql)<br><br> sql = '''<br> CREATE TABLE t2<br> (<br> kid INTEGER PRIMARY KEY,<br> c1 TEXT,<br> c2 TEXT<br>
)'''<br> cur.execute(sql)<br><br> sql = '''<br> CREATE TABLE t3<br> (<br> kid INTEGER PRIMARY KEY,<br> c1 TEXT,<br> c2 TEXT<br>
)'''<br> cur.execute(sql)<br><br> con.commit()<br> except sqlite3.Error:<br> print("ERROR: createdb did not commit.", file=sys.stderr)<br> print("tried this sql:", file=sys.stderr)<br>
print(sql, file=sys.stderr)<br> raise<br> finally:<br> cur.close()<br> con.close()<br><br>if __name__ == '__main__':<br> createdb('myDbName')<br></code><br><br>This script will run once without errors.<br>
If you run it a second time, you get:<br><br><console output><br>ERROR: createdb did not commit.<br>tried this sql:<br><br> CREATE TABLE t1<br> (<br> kid INTEGER PRIMARY KEY,<br> c1 TEXT,<br>
c2 TEXT<br> )<br>Traceback (most recent call last):<br> File "x.py", line 44, in <module><br> createdb('myDbName')<br> File "x.py", line 14, in createdb<br>
cur.execute(sql)<br>
sqlite3.OperationalError: table t1 already exists<br></console output><br><br>Which is exactly what you should expect. Note that using the naked "raise" statement results in a higher quality traceback with error text pinpointing the problem. <br>
<br>I used print as a function, so this example should work in python versions from 2.6 to 3.2.<br>--<br>Vernon<br><br></div></div>