将dict对象添加到postgresql

Adding dict object to postgresql

所以我在 Python3.5 上使用 psycopg2 将一些数据插入到 postgresql 数据库中。我想做的是有两列是字符串,最后一列只是一个字典对象。我不用查字典,直接从数据库里拉出来用就行了

例如:

uuid = "testName"
otherString = ""
dict = {'id':'122','name':'test','number':'444-444-4444'}

# add code here to store two strings and dict to postgresql

cur.execute('''SELECT dict FROM table where uuid = %s''', 'testName')
newDict = cur.fetchone()
print(newDict['number'])

这可能吗?如果可以,我该怎么做?

如果你的 PostgreSQL 版本足够新(9.4+)并且 psycopg 版本 >= 2.5.4 所有键都是字符串并且值可以表示为 JSON,最好将其存储到JSONB 列。然后,如果需要,该列也可以搜索。只需将 table 创建为

CREATE TABLE thetable (
    uuid TEXT,
    dict JSONB
);

(...并根据需要自然添加索引、主键等...) 将字典发送到 PostgreSQL 时,你只需要用 Json 适配器包装它;当从 PostgreSQL 接收时,JSONB 值将自动转换为字典,因此插入将变为

from psycopg2.extras import Json, DictCursor

cur = conn.cursor(cursor_factory=DictCursor)

cur.execute('INSERT into thetable (uuid, dict) values (%s, %s)',
    ['testName', Json({'id':'122','name':'test','number':'444-444-4444'})])

和 selecting 就像

一样简单
cur.execute('SELECT dict FROM thetable where uuid = %s', ['testName'])
row = cur.fetchone()
print(row['dict']) # its now a dictionary object with all the keys restored
print(row['dict']['number']) # the value of the number key

使用 JSONB,PostgreSQL 可以比将字典转储为文本更有效地存储值。此外,可以对数据进行查询,例如 select JSONB 列中的一些字段:

>>> cur.execute("SELECT dict->>'id', dict->>'number' FROM thetable")
>>> cur.fetchone()
['122', '444-444-4444']

或者您可以根据需要在查询中使用它们:

>>> cur.execute("SELECT uuid FROM thetable WHERE dict->>'number' = %s',
    ['444-444-4444'])
>>> cur.fetchall()
[['testName', {'id': '122', 'name': 'test', 'number': '444-444-4444'}]]

您可以在存储数据之前使用JSON序列化数据:

import json

data = json.dumps({'id':'122','name':'test','number':'444-444-4444'})

然后在检索代码时将其反序列化:

cur.execute('SELECT dict from ....')
res = cur.fetchone()

dict = json.loads(res['dict'])
print(dict['number'])