pysqlite - Checking the existance of a table

Gerhard Häring gh at
Sat Jun 18 15:58:27 CEST 2005

rh0dium wrote:
> Hi all,
> I am starting to play with pysqlite, and would like to know if there is
> a function to determine if a table exists or not.

You can try to access the table in a try-catch block, something like:

cur.execute("select * from tablename where 1=2")

and check if it fails.

Or you can query the sqlite_master table (don't know any specification 
off-hand, but it contains the schema information).

Instead of doing a select on sqlite_master, you can use "pragma 
table_info", which returns information for each column in the table, 
and, apparently, an empty list if the table does not exist:

 >>> cur.execute("pragma table_info(foo)")
 >>> print cur.fetchall()
[(0, u'bar', u'integer', 0, None, 0)]

 >>> cur.execute("pragma table_info(foo_does_not_exist)")
 >>> print cur.fetchall()


-- Gerhard

More information about the Python-list mailing list