I had a list of dictionaries called xyz
[
{
"x": -11.370502,
"y": -8.545141,
"z": -0.083815
},
{
"x": -11.36693,
"y": -8.403456,
"z": -0.081571
},
{
"x": -11.353832,
"y": -7.935539,
"z": -0.074171
},
{
"x": -11.315733,
"y": -7.325937,
"z": -0.06436599999999999
},
{
"x": -11.266916,
"y": -6.716335,
"z": -0.054387000000000005
},
{
"x": -11.185953,
"y": -6.106733,
"z": -0.043016
},
{
"x": -11.094276,
"y": -5.497132,
"z": -0.030890999999999995
},
{
"x": -10.982357,
"y": -4.88753,
"z": -0.018994999999999998
}
]
I wrote this to my sqlite3
-database using
sqlite3.Binary(pickle.dumps(border, protocol=-1))
Now I want to read it back it from the db.
xyz = bytes(sqlite3_xyz)
What's the next step?
CodePudding user response:
You just need to reverse the steps.
test.py:
import pickle
import sqlite3
XYZ = [
{"x": -11.370502, "y": -8.545141, "z": -0.083815},
{"x": -11.36693, "y": -8.403456, "z": -0.081571},
{"x": -11.353832, "y": -7.935539, "z": -0.074171},
{"x": -11.315733, "y": -7.325937, "z": -0.06436599999999999},
{"x": -11.266916, "y": -6.716335, "z": -0.054387000000000005},
{"x": -11.185953, "y": -6.106733, "z": -0.043016},
{"x": -11.094276, "y": -5.497132, "z": -0.030890999999999995},
{"x": -10.982357, "y": -4.88753, "z": -0.018994999999999998},
]
def main():
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t1 (data BLOB)")
data = sqlite3.Binary(pickle.dumps(XYZ))
with con:
cur.execute("INSERT INTO t1 VALUES (?)", (data,))
for row in cur.execute("SELECT data FROM t1"):
data, *_ = row
print(pickle.loads(data)[0])
con.close()
if __name__ == "__main__":
main()
Test:
$ python test.py
{'x': -11.370502, 'y': -8.545141, 'z': -0.083815}
The security principles for unpickling data from unknown source still applies here:
Warning
The
pickle
module is not secure. Only unpickle data you trust.