I am trying to append records to a sqlite db file in a table, first checking if the db file exists and then checking if the table exists. If not create the db and table file dynamically.
CodePudding user response:
I hope you are using sqlite3 library, in that if you use connect method it will do exactly what you want.find the db or else create it.
CodePudding user response:
Expanding on to answer by @Umang, you could check for the table's existence using a query as SELECT count(*) FROM sqlite_master WHERE type='table' AND name='table_name';
.
CodePudding user response:
What you typically do is simply:
import sqlite3
con = sqlite3.connect('example.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS ...''')
If example.db
exists, it'll be used, otherwise it'll be created.
If the table already exists, the CREATE TABLE
command will do nothing, otherwise it'll create the table. Done.