sqlite newbie question - how to know if a table exists?

Gerhard Häring gh at ghaering.de
Fri Jun 22 06:07:21 EDT 2007


kf9150 at gmail.com wrote:
> Hello,
> 
> Another newbie question: How do I know if there is a table with
> certain name in a sqlite database? What i'm doing now is just create
> the table with that name, if exception occurs, that means the table is
> already created. Am i correct? Any better way? Thank you.

That approach is ok. If your SQLite library is recent enough (I don't 
know the exact version), you can use "create table if not exists ...".

For older SQLite releases, you can check like this:

len(con.execute("pragma table_info(?)", ("tablename",)).fetchall()) > 0

or

con.execute("select count(*) from sqlite_master where name=?",
   ("tablename" ,)).fetchone()

-- Gerhard



More information about the Python-list mailing list