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

K

kf9150

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.

kelie
 
?

=?ISO-8859-1?Q?Gerhard_H=E4ring?=

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
 
K

kf9150

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 ...".
-- Gerhard


Thanks Gerhard. I'm using sqlite3 that came with Python2.5
installation. So "create table if not exists" works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top