问题
I have a python script which creates some objects. I would like to be able to save these objects into my postgres database for use later.
My thinking was I could pickle an object, then store that in a field in the db. But I'm going round in circles about how to store and retrieve and use the data.
I've tried storing the pickle binary string as text but I can't work out how to encode / escape it. Then how to load the string as a binary string to unpickle.
I've tried storing the data as bytea both with psycopg2.Binary(data) and without.
Then reading into buffer and encoding with base64.b64encode(result) but it's not coming out the same and cannot be unpickled.
Is there a simple way to store and retrieve python objects in a SQL (postgres) database?
回答1:
Following the comment from @SergioPulgarin I tried the following which worked!
N.B Edit2 following comment by @Tomalak
Storing:
Pickle the object to a binary string
pickle_string = pickle.dumps(object)Store the pickle string in a bytea (binary) field in postgres. Use simple
INSERTquery in Psycopg2
Retrieval:
Selectthe field in Psycopg2. (simpleSELECTquery)Unpickle the decoded result
retrieved_pickle_string = pickle.loads(decoded_result)
Hope that helps anybody trying to do something similar!
来源:https://stackoverflow.com/questions/57642165/saving-python-object-in-postgres-table-with-pickle