如果您的 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'}]]