I want to list all the tables of a sqlite3 database, but it doesn’t work. Let’s imagine that in ma database I have the following tables : foo1, foo2, foo3, … Then, with this code :
cur.execute("SELECT name FROM sqlite_master")
for table in cur:
print("The table is", table[0])
I have this output : The table is foo1, whereas I’d like have this one :
The table is foo1
The table is foo2
The table is foo3
…
But if I modify the code to have :
cur.execute("SELECT name FROM sqlite_master")
print(cur.fetchone())
for table in cur:
print("The table is", table[0]
Then the output is :
(foo1,)
The table is foo2
So what’s wrong in my code ?
Your first method should have worked (assuming FTOM is FROM):
import sqlite3
connection = sqlite3.connect(':memory:')
cur = connection.cursor()
cur.execute('CREATE TABLE foo1 (bar INTEGER, baz TIMESTAMP)')
cur.execute('CREATE TABLE foo2 (bar INTEGER, baz TIMESTAMP)')
cur.execute('CREATE TABLE foo3 (bar INTEGER, baz TIMESTAMP)')
cur.execute(
"SELECT name FROM sqlite_master")
for table in cur:
print(table[0])
prints
foo1
foo2
foo3
Note, to exclude indices, be sure to add WHERE type='table' to the SQL query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With