pysqlite - Checking the existance of a table

R

rh0dium

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.


Thanks
 
M

Matthias Kluwe

Simply use the internal table SQLite_Master:

select name from SQLite_Master

will return all existing tables.

Regards,
Matthias
 
C

Cousin Stanley

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

rh0dium ....

One way to get at a list of table names
in an SQLite data base is to query
the sqlite_master table ....


import sys
import sqlite

this_db = sys.argv[ 1 ]

list_sql = [ "select tbl_name" ,
"from sqlite_master" ]

str_sql = '\n'.join( list_sql )

dbc = sqlite.connect( db = "%s" % this_db )

curs = dbc.cursor()

curs.execute( str_sql )

list_tables = curs.fetchall()

print '\n Table Names in SQLite DB .... %s \n' % ( this_db )

for table_name in list_tables :

print " %s " % ( table_name )

print

dbc.close()
 
?

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

rh0dium said:
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:
[(0, u'bar', u'integer', 0, None, 0)]
[]

HTH,

-- Gerhard
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top