使用Python导入JSON至PostgreSQL时遇语法错误求助
问题:Python批量导入JSON到PostgreSQL时出现语法错误
我的Python代码
import json import psycopg2 con = psycopg2.connect(database="kw_du", user="postgres", password="f67dd8hzFE5",host="localhost") cur = con.cursor() with open(r"C:\Users\diego\OneDrive\Desktop\Workplace\220906\nu_2022_09_01.json", 'r') as data_file: data = json.load(data_file) with con.cursor() as cur: cur.executemany('INSERT INTO test_nu(vp_ip, system_activ, vpm_activ) VALUES(%s)', [(json.dumps(d),) for d in data]) con.commit() con.close()
JSON文件结构
[{"vp_id":1,"system_activ":1,"vpm_activ":1},{"vp_id":2,"system_activ":2,"vpm_activ":2}]
执行时的错误信息
line 13, in
cur.executemany('INSERT INTO test_nu (vp_id, system_aktiv) VALUES(%s)', [(json.dumps(d),) for d in data])
psycopg2.errors.SyntaxError: ERROR: INSERT has more target columns than expressions
LINE 1: INSERT INTO test_nu (vp_id, system_aktiv) VALUES('{"vp_id": ...
疑问
我知道这个错误可能有多种原因,但一直解决不了,怀疑是不是单引号或大括号导致JSON没被正确解析,求解决提示。
解决提示
- 核心问题并非JSON解析,是INSERT语句列数不匹配:你写的INSERT语句指定了2列(
vp_id, system_aktiv),但仅提供1个表达式(%s),PostgreSQL无法将单个JSON字符串映射到多列,直接触发列数不匹配报错。 - 针对场景的两种解决方式:
- 拆分JSON字段匹配表列:若
test_nu表是普通数据列(非JSON类型),需将每个JSON对象的字段拆分后对应表列:# 假设表列是vp_id, system_activ, vpm_activ cur.executemany( 'INSERT INTO test_nu(vp_id, system_activ, vpm_activ) VALUES(%(vp_id)s, %(system_activ)s, %(vpm_activ)s)', data # 直接传入解析后的JSON列表,psycopg2会自动匹配字典键与占位符 ) - 适配JSON类型表列:若表中有JSON类型的列(比如命名为
json_data),则INSERT语句仅需指定该列,传入JSON字符串即可:cur.executemany( 'INSERT INTO test_nu(json_data) VALUES(%s)', [(json.dumps(d),) for d in data] )
- 拆分JSON字段匹配表列:若
- 额外注意:代码与错误信息中的列名存在拼写差异——代码写的是
system_activ,错误信息里是system_aktiv,需确认数据库表的实际列名,避免拼写错误。
内容的提问来源于stack exchange,提问作者Anthony Admin
相关产品推荐
相关产品推荐

