列出数据库的表

25 浏览
0 Comments

列出数据库的表

这个问题已经有了答案:

如何列出使用 ATTACH 打开的 SQLite 数据库文件中的表格?

我想列出 sqlite3 数据库的所有表格,但是它不起作用。

假设在我的数据库中有以下表格:foo1,foo2,foo3,...

然后,通过这段代码:

cur.execute("SELECT name FROM sqlite_master")
for table in cur:
     print("The table is", table[0])

我得到这个输出:The table is foo1,但我希望得到这个输出:

The table is foo1
The table is foo2
The table is foo3
…

但是,如果我修改代码,改成:

cur.execute("SELECT name FROM sqlite_master")
print(cur.fetchone())
for table in cur:
     print("The table is", table[0]

那么输出就是:

(foo1,)
The table is foo2

所以我的代码有什么问题吗?

admin 更改状态以发布 2023年5月22日
0
0 Comments

你的第一个方法应该能够起作用(假设FTOMFROM):

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])

输出

foo1
foo2
foo3

请注意,为了排除索引,请确保在SQL查询中添加WHERE type='table'

0