添加对象 dict 在 postgresql

所以我使用 psycopg2 在 Python3.5, 在数据库中插入一些数据 postgresql. 我想做什么 - 它是两列是行,最后一列只是一个对象 dict. 我不需要寻找听写,只需要将其拉出数据库并使用。

例如:


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. 然后,如果需要,则该列也可用于搜索。 只需创建一个表就像


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'}/]/


这就是简单的


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 可以更有效地存储值,而不是简单地折扣文本形式的字典。 另外,可以使用数据执行请求,例如,从列中选择某些字段 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']/

要回复问题请先登录注册