LinnK
LinnK

Reputation: 395

Show Tables in SQLite Database in Python

I know this is a very basic question but for some reason I can't get past this one error. I'm trying to show/put all the names of the tables in a database (named 'GData.db') into a variable available_tables in Python. Currently I have the following:

con = sql.connect(r'/Users/linnk/Desktop/Results/GData.db')
cur = con.cursor() 
cur.execute("SHOW TABLES IN GData")
available_table=(cursor.fetchall())

This gives me the following error for the second-last line:

OperationalError: near "SHOW": syntax error

I've looked at the SHOW TABLES documentation as well as around the web but not found information that helps me.

Upvotes: 5

Views: 20313

Answers (1)

chucksmash
chucksmash

Reputation: 6017

The query to list tables in a Sqlite database:

SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;

So your snippet becomes:

con = sql.connect(r'/Users/linnk/Desktop/Results/GData.db')
mycur = con.cursor() 
mycur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
available_table=(mycur.fetchall())

See the Sqlite FAQ for more info.

Upvotes: 17

Related Questions