如果您的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, DictCursorcur = 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 restoredprint(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'}]]