Shniper Shniper - 3 months ago 37
Python Question

Check if sql table exists in python

I am making a python application for a voting system. I am using

to create a database which is stored locally on the user's machine.

I need a way to check if a table exists or not because the tables need to get created on each user's database file when they run the application but if the application is run when the tables exist and I just have a statement creating the tables it will run an error because the table already exists.

Here is some simplified sample code

conn = sqlite3.connect('firefight')
c = conn.cursor()
if table 'info' exists:
#do nothing
c.execute("CREATE TABLE info(PRIMARY KEY id int, username text, password text)")


I think there are two options here. First, SQLite has a statement which would create the table only if it does not exist:

CREATE TABLE IF NOT EXISTS info(PRIMARY KEY id int, username text, password text)")

But if you want a more database generic way to handle this, you could simply execute a regular CREATE TABLE statement and then handle the exception in Python.