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

Insert small dictionary like {1:23, 2:45, 3:17} into a column of SQL database table in Postgres using python language

我有一个 table 具有一个 varchar 类型的列和 2 个 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...

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

在 table 中应该是这样的:

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}

要将数据插入 JSON 列,您必须确保数据采用有效的 JSON 格式,例如

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

所以您可能必须序列化为 JSON 将字典格式设置为:

import json

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+"', '" + json.dumps(step_count_dict) + "', '" + json.dumps(speed_dict) + "'); "

我建议不要“拼接”您的 sql 查询。如果您养成习惯,这可能会让您遭受注入攻击。

像这样使用pythonsqlapi,假设你有一个cur.execute('SQL CODE w/ insertions as ? ? ?', (tupel, of, substitutions):[=13形式的游标(cur) =]

cur.execute('INSERT INTO global_records(cattle_id, step_count, speed) VALUES (?,?,?)', (cattle_id, step_count_dict, speed_dict))

您正在使用的数据库库应该能够弄清楚如何将给定的变量解析为正确的形式,以便将您的行插入到您正在使用的 sql 数据库中。

请勿通过将字符串拼接在一起来构成查询。这几乎肯定会导致安全漏洞。

psycopg2 库具有非常好的 JSON 支持,文档中有清晰的示例。即使您想忽略 JSON 支持,也可以在查询中使用占位符。

docs 中所述,只需将 json.dumps 用于 json 数据(序列化为字符串)并让 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})]