[Tutor] How to test for the existence of a table in a sqlite3 db?

boB Stepp robertvstepp at gmail.com
Sun Oct 15 01:48:27 EDT 2017


On Sun, Oct 15, 2017 at 12:07 AM, boB Stepp <robertvstepp at gmail.com> wrote:

> ================================================================================
> #!/usr/bin/env python3
>
> """This file starts the blood pressure readings program."""
>
> import sqlite3
>
> def ensure_db(filename):
>     """Open the database, "filename", if it exists; otherwise, create a
>     database named "filename"."""
>
>     db = sqlite3.connect(filename)
>     cur = db.cursor()
>
>     try:
>         sql_cmd = "SELECT VersionNumber FROM CurrentDBVersion"
>
>         # First element of returned tuple will be the db version number:
>         current_db_version = int(cur.execute(sql_cmd).fetchone()[0])
>
>     except sqlite3.OperationalError:
>         # This means that the database and the table, "CurrentDBVersion", has
>         # not yet been created, implying "version 0".
>         current_db_version = 0
>
>     finally:
>         sql_scripts = ["../database/create_sqlite3_db.sql"]
>         for sql_scriptname in sql_scripts[current_db_version:]:
>             with open(sql_scriptname) as f:
>                 cur.executescript(f.read())
>
>     return db

I have not used a "finally" block before.  I just had the thought that
maybe it would run even if an uncaught exception might occur.  I tried
to test this thought by generating a deliberate NameError in the "try"
block and added a print to the "finally" clause.  I got the intended
NameError with no evidence of the added print printing.  But I thought
I would ask just to be sure:  If an uncaught exception occurs, will
the "finally" clause execute?

>
> I have chickened out and not done a TDD approach yet.  I will probably
> pause here, wait for feedback from this list, and try to figure out
> how I should test what I have so far.  And how do you test SQL scripts
> anyway?
>
> Some things I am still pondering:

I forgot to add (5):

5)  How should I handle the cursor object?  When I should I close it?
My function returns "db" which I presume keeps the connection to the
database.  But what happens to the cursor object as I have written the
function, since I never closed it?


-- 
boB


More information about the Tutor mailing list