How do I check if the database file already exists or not? And, if the it exists, how do I check if it already has a specific table or not?
Asked
Active
Viewed 4,266 times
1 Answers
10
To see if a database exists, you can sqlite3.connect
to the file that you think contains the database, and try running a query on it. If it is not a database, you will get this error:
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
sqlite3.connect
will create the database if it doesn't exist; as @johnp points out in the comments, os.path.exists
will tell you whether the file exists.
To check for existing tables, you query against sqlite_master. For example:
>>> def foo(name):
... for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
... if row == (name,):
... return True
... return False
...
>>> foo("tz_data")
True
>>> foo("asdf")
False

Mark Rushakoff
- 249,864
- 45
- 407
- 398
-
1hmm... does calling sqlite3.connect() automatically create the database? – john2x Oct 04 '09 at 14:57
-
If you want to see if the file exists, use os.path.exists(): import os.path os.path.exists('dbname.db') Perform this check before you sqlite3.connect() to avoid creating the database if it does not exist. – John Paulett Oct 04 '09 at 16:06
-
Sorry--formatting code in comments didn't go well, but you should get the idea. – John Paulett Oct 04 '09 at 16:07