python操作postgresql存储json与列表数据

本文介绍如何使用Python与PostgreSQL交互,包括创建包含JSON和列表字段的表、插入JSON数据、存储和查询列表数据的方法。还介绍了直接使用SQL进行数据操作的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己摸索瞎记录的,以备下次使用,有知道更好方法,请指出

1. 建表sql

CREATE TABLE table_name (
    aaa json NULL,
	bbb json[] NULL,
	ccc text[] NULL)

2. 插入sql

    (1) 存储json

          保存时,先dumps,然后传参存储,查询后再loads

import json

from psycopg2.extras import Json

cur = conn.cursor()
params = {"a":1, "b":2}
cur.execute('insert into table_name(aaa) values (%s)',[json.dumps(params)])

(2)存储list

        dict数组

dict_list = [{"a": 1},{"b": 2}]
# 我的做法,不dumps,会报错...dict....,dumps时,加入ensure_ascii,不会将中文转为unicode
new_dict_list = [json.dumps(tmp, ensure_ascii=False) for tmp in dict_list]
insert_sql = 'insert into table_name(bbb) values (%s::json[])' % new_dict_list 

      text,varchar数组未测试,原理上应该跟json一样,下次亲测后更新......

(3) 数组中是字符串查询(数组中是否包含某值)

sql = "select * from table_name where '123'=any(ccc)"


# 取数组中元素,索引从1开始
sql = "select ccc[1] from table_name"

(4) 数组中是json对象,根据json中的字段查询

  • -> 操作符:它会提取 JSON 对象中的值,并保持该值的原始数据类型。
  • ->> 操作符:它会提取 JSON 对象中的值,但无论原始数据类型是什么,提取出的结果都会被转换为文本类型

 使用发现:取值时,两个都可以使用,做判断时,只能使用->>

sql = "select * from table_name where bbb->>id='1'"

3. 不使用python,原始插入

用单引号
insert into test values(1,'{1,2,3}');
insert into test values(2,'{4,5,6}');
用array
insert into test values(3,array[7,8,9]);
insert into test values(4,array[4,5,6]);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值