I am trying to understand SQLite3 by playing with storage and retrieval of dictionaries. Tutorials everywhere indicate that I should just get data back as integers (as it was entered) but I keep getting an "undecodable" byte string:
>>> ['\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')
What am I missing?
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()
Got it to work using connection.row_factory = sqlite3.Row
then:
rows = cursor.fetchall()
for row in rows:
print(row[1])
print(row['A'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.