使用Python语言将像{1:23,2:45,3:17}这样的小词典插入到Postgres中的SQL数据库表的列中

2022-04-14 00:00:00 python postgresql json psycopg2 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})]

相关文章