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

boB Stepp robertvstepp at gmail.com
Sat Oct 14 03:11:44 EDT 2017

On Sat, Oct 14, 2017 at 1:43 AM, boB Stepp <robertvstepp at gmail.com> wrote:

> I am currently trying to make the following work:
> py3: tb_exists = c.execute('select name from sqlite_master where type="table"')
> so that I can embed this in an if statement.  But it is not behaving
> quite like I hope yet.  So I am still experimenting and Googling ...

I'm tired and not thinking clearly anymore, but I think I have
something to give me the basis of what I want to do.  First, what
happens if the table does *not* exist:

py3: import sqlite3
py3: conn = sqlite3.connect(':memory:')
py3: c = conn.cursor()
py3: tb_exists = "select name from sqlite_master where type='table'
and name='test'"
py3: tb_ck = c.execute(tb_exists).fetchone()
py3: tb_ck
py3: print(tb_ck)

So I get "None" as a result if the target table has not been created
yet.  But if I *do* create the table I want:

py3: with open('create_sqlite3_db.sql') as f:
...     sql = f.read()
py3: c.executescript(sql)
<sqlite3.Cursor object at 0x00000000026B4490>
py3: tb_exists = "select name from sqlite_master where type='table'
and name='BloodPressureReadings'"
py3: tb_ck = c.execute(tb_exists).fetchone()
py3: print(tb_ck)

So it is looking like I can use this technique to determine if I need
to create the BloodPressureReadings table or not.  Am I on track here
or is there a better technique?


More information about the Tutor mailing list