在 Postgresql (Psycopg2) 中存储腌制字典

Storing a pickled dictionary in Postgresql (Psycopg2)

我正在尝试在 Postgresql 中存储腌制的嵌套字典(我知道这是一种快速且肮脏的方法,并且无法从 Postgresql 访问字典内容 - 通常是不好的做法)

# boilerplate, preamble and upstream work.
import psycopg2


''' Inputs: nd = dictionary to be pickled '''



pickled = pickle.dumps(nd)

connection = psycopg2.connect(user = "-----",
                              password = "----",
                              host = "----",
                              port = "----",
                              database = "----")
    
name = 'database1'    
    
    
print('Connected...')
cursor = connection.cursor()
print(connection.get_dsn_parameters(),"\n")
cursor.execute("CREATE TABLE thetable (name TEXT, ablob BYTEA)")
print('Created Table...')
cursor.execute("INSERT INTO thetable VALUES(%s)",(psycopg2.Binary(pickled),))
connection.commit()
print('Added Data...')
cursor.close()
connection.close()
print('Connection closed...')

当我进行数据检索时,我在从 Postgres 导入数据时遇到了很多问题 - 本质上是要打开数据,将其解封回字典并可视化。我试过:

import psycopg2
from io import BytesIO

connection = psycopg2.connect(user = "----",
                              password = "----",
                              host = "----",
                              port = "----",
                              database = "----")

cursor = connection.cursor()
cursor.execute("SELECT ablob FROM thetable")
result, = cursor.fetchone()
cursor.close()
connection.rollback()

result = BytesIO(result)

print(pickle.load(result))

按照这个 link:https://www.oreilly.com/library/view/python-cookbook/0596001673/ch08s08.html, and consulted: Insert an image in postgresql database and: saving python object in postgres table with pickle,但是无法 return 腌制字典。

非常感谢任何有助于实现这一目标的建议!

当您的 CREATE TABLE 列出两个字段时,您必须在 INSERT 中列出要填写的字段,除非您全部填写。

import psycopg2
import pickle

dict = {
  "foo": "bar"
}

p = pickle.dumps(dict)

connection = psycopg2.connect(database = "test")

cursor = connection.cursor()
cursor.execute("CREATE TABLE thetable (name TEXT, ablob BYTEA)")
cursor.execute("INSERT INTO thetable VALUES(%s,%s)",('test',p))
connection.commit()
cursor.close()
connection.close()

和阅读

import psycopg2
import pickle

connection = psycopg2.connect(database = "test")

cursor = connection.cursor()
cursor.execute("SELECT ablob FROM thetable WHERE name='test';")
result = cursor.fetchone()

print pickle.loads(result[0])

cursor.close()
connection.close()