Shniper Shniper - 19 days ago 5
Python Question

Check if sql table exists in python

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

sqlite3
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
else:
c.execute("CREATE TABLE info(PRIMARY KEY id int, username text, password text)")

Answer

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.

Comments