如何在python中打印sqlite3的输出

dy2hfwbg  于 2023-08-06  发布在  SQLite
关注(0)|答案(2)|浏览(151)

下面是我的代码:

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

字符串
当我运行它时,我得到了这样的输出:

sqlite3.Cursor对象在0x02889FAO

如何打印实际的sqlite3输出?

bvk5enib

bvk5enib1#

你应该取得成果。下面是工作示例:

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)

zrfyljdw

zrfyljdw2#

如果我需要使用带列名的数据,而不是按id,那么所选的答案不适合我。如果我们使用返回列值的输出,那么我们也会得到sqlite3.Row对象,而不是list。我们必须将结果转换为dict,以便可以通过打印显示。

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

字符串

相关问题