[Tutor] How to test for the existence of a table in a sqlite3 db?
boB Stepp
robertvstepp at gmail.com
Sat Oct 14 02:43:54 EDT 2017
On Sat, Oct 14, 2017 at 1:27 AM, srinivas devaki
<mr.eightnoteight at gmail.com> wrote:
> SQL has "CREATE TABLE IF NOT EXISTS"
>
> so you change your instructions to
> ```python
> import sqlite3
> conn = sqlite3.connect(':memory:')
> c = conn.cursor()
> c.execute("""
> CREATE TABLE IF NOT EXISTS BloodPressureReadings (
> ReadingID INTEGER PRIMARY KEY,
> Date TEXT,
> Time TEXT,
> SystolicBP INTEGER,
> DiastolicBP INTEGER,
> Comments TEXT);
> """)
> c.execute("SELECT * FROM BloodPressureReadings")
But I do *not* want to create this table from within my python code;
instead, I want to run the table creation commands from a file if the
table does not already exist. This way I have more flexibility if I
later change to different database products, for testing purposes,
etc.
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 ...
boB
More information about the Tutor
mailing list