[英]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.