用Python SQLite3,我可以以什么方式知道.db文件中的表格?

12 浏览
0 Comments

用Python SQLite3,我可以以什么方式知道.db文件中的表格?

以下是代码:

import sqlite3
cx = sqlite3.connect("test.db")
cu = cx.cursor()
# 创建表1
cu.execute("create table user_info1 (user_id text primary key,followers integer, asks integer, answers integer, goods integer)")
# 创建表2
cu.execute("create table user_info2 (user_id text primary key,followers integer, asks integer, answers integer, goods integer)")

现在我想知道test.db中有多少个表:

cu.execute('.tables') # 不能工作
cu.execute('select * from test.sqlite_master where type = "table"')
# OperationalError: no such table: test.sqlite_master

以上方法对我无效。有什么提示吗?谢谢!

0
0 Comments

问题的原因是数据库名称不是"test",而是"main"。解决方法是使用以下代码来查询数据库中的表格:

cu.execute("SELECT * FROM sqlite_master WHERE type = 'table'")

"main" 是默认的数据库名称,所以你甚至不需要指定它。感谢,非常清楚。

0