如何在 Python 中打印 SQLite 3 的输出

问题描述 投票:0回答:2

这是我的代码:

conn = sqlite3.connect('myfile.db')
print(conn.execute("PRAGMA table_info(mytable);"))

当我运行该命令时,我得到了以下输出:

sqlite3.Cursor 对象位于 0x02889FAO

如何打印实际的 SQLite 3 输出?

python printing sqlite
2个回答
5
投票

您应该获取结果。 这是工作示例:

import sqlite3

conn = sqlite3.connect('myfile.db')
cursor = conn.execute("PRAGMA table_info(mytable);")
results = cursor.fetchall()
print(results)

或带有漂亮的印刷品:

import sqlite3
from pprint import pprint

conn = sqlite3.connect('myfile.db')
cursor = conn.execute("PRAGMA table_info(mytable);")
results = cursor.fetchall()
pprint(results)

0
投票

如果您更喜欢通过列名而不是索引访问数据,则提供的解决方案将不适合。获取输出时,SQLite 通常返回一个

sqlite3.Row
对象而不是
list
。要轻松查看和打印此输出,您需要将结果转换为字典。

具体操作方法如下:

import sqlite3 as sl

con = sl.connect('db.sqlite')
con.row_factory = sl.Row
rows = con.execute('SELECT * FROM table').fetchall()

for row in rows:
     print(dict(row))
     print(row['column_name'])
© www.soinside.com 2019 - 2024. All rights reserved.