使用Python语言将像{1:23,2:45,3:17}这样的小词典插入到Postgres中的SQL数据库表的列中 [英] Insert small dictionary like {1:23, 2:45, 3:17} into a column of SQL database table in Postgres using python language

查看:20
本文介绍了使用Python语言将像{1:23,2:45,3:17}这样的小词典插入到Postgres中的SQL数据库表的列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,它有一个varchar类型的列和两个json类型的列,这是我使用以下命令创建的:

create table global_records(
     cattle_id varchar(255) not null primary key, 
     step_count json, 
     speed json
);

我现在想使用python插入如下所示的值:

INSERT INTO 
       global_records(cattle_id, step_count, speed) 
VALUES ('cattle_A', '{1: 22, 4: 12}', '{2: 24, 6: 98}');

我为它编写了一个如下所示的python字符串来执行:

cattle_id = 'cattle_A'
step_count_dict = {1: 22, 4: 12}
speed_dict = {2: 24, 6: 98}

query = "INSERT INTO global_records(cattle_id, step_count, speed) VALUES ('"+cattle_id+"', '" + str(step_count_dict) + "', '" + str(speed_dict) + "'); "

但这不起作用。我收到以下错误:

invalid input syntax for type json
    LINE 1: ... step_count) values ('cattle_A', '{1: 22}',...
                                                             ^
DETAIL:  Expected string or "}", but found "1".
CONTEXT:  JSON data, line 1: {1...

我搜索了类似的答案,但没有找到。这应该很简单。

它在表中应该是这样的:

cattle_id |   step_count   |    speed
----------+----------------+----------------
cattle_A  | {1: 22, 4: 12} | {2: 24, 6: 98}
cattle_B  | {4: 92, 6: 90} | {88: 4, 12: 23}

推荐答案

只需对docs中提到的json数据使用json.dumps(序列化为字符串),让psycopg2完成所有工作和参数绑定:

cattle_id = 'cattle_A'
step_count_dict = json.dumps({1: 22, 4: 12})
speed_dict = json.dumps({2: 24, 6: 98})

cur = con.cursor()
query = "INSERT INTO global_records(cattle_id, step_count, speed) VALUES (%s, %s, %s)"
cur.execute(query, (cattle_id, step_count_dict, speed_dict))
con.commit()

cur.execute('Select * from global_records')
print(cur.fetchall())

输出:

[('cattle_A', {'1': 22, '4': 12}, {'2': 24, '6': 98})]

这篇关于使用Python语言将像{1:23,2:45,3:17}这样的小词典插入到Postgres中的SQL数据库表的列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆