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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top