[英]Python: SQLite3 Retrieving data as bytes and unable to convert
我试图通过存储和检索字典来理解 SQLite3。 随处可见的教程表明我应该将数据作为整数取回(输入时),但我不断得到一个“不可解码”的字节字符串:
>>> ['\x01\x00\x00\x00\x00\x00\x00\x00', '\x03\x00\x00\x00\x00\x00\x00\x00', '\x02\x00\x00\x00\x00\x00\x00\x00'] (b'\x02\x00\x00\x00\x00\x00\x00\x00', b'\x02\x00\x00\x00\x00\x00\x00\x00', b'\x01\x00\x00\x00\x00\x00\x00\x00')
我错过了什么?
import json
import sqlite3
import pandas as pd
path_prefix = "..."
test_dict = {'A': [1,2,3],
'B': [3,2,1],
'C': [2,1,3]}
obj = open(path_prefix+"json_file.json", "w")
json.dump(test_dict, obj, indent=4)
obj.close()
connection = sqlite3.connect(path_prefix+'db.sqlite', detect_types=sqlite3.PARSE_DECLTYPES)
cursor = connection.cursor()
cursor.execute('Create Table if not exists Test (A integer, B integer, C integer)')
content = json.loads(open(path_prefix+'json_file.json').read())
test_df = pd.DataFrame.from_dict(content)
print(test_df)
for i in range(len(test_df)):
print(tuple(test_df.iloc[i].values))
cursor.execute('insert into Test values(?,?,?)', tuple(test_df.iloc[i].values))
connection.commit()
cursor.execute('SELECT * FROM Test')
print([t.decode() for t in cursor.fetchone()])
print(cursor.fetchone())
connection.close()
然后使用connection.row_factory = sqlite3.Row
让它工作:
rows = cursor.fetchall()
for row in rows:
print(row[1])
print(row['A'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.