栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

将dict对象添加到Postgresql

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将dict对象添加到Postgresql

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


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号