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

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


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

> 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)
> ('BloodPressureReadings',)
>
> 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?

It just occurred to me after sending the above, does something like
"sqlite_master" exist for other database programs than sqlite3?  Can I
abstract out "sqlite_master" and replace it with a variable so that I
can handle any kind of database?


-- 
boB


More information about the Tutor mailing list