如何使用Pandas的to_sql向PostgreSQL插入包含列表的单元格
问题原因排查
- 依赖不匹配:你当前导入了MySQL驱动
pymysql,连接PostgreSQL需要使用psycopg2-binary作为底层驱动 - 类型映射缺失:pandas默认无法自动识别存储列表的列,不会主动映射为PostgreSQL的数组类型,导致插入静默失败
- 代码逻辑错误:你创建的连接变量名为
con,但finally块中关闭的是未定义的connection,且插入操作默认未提交事务,数据不会真正写入数据库
解决步骤
安装PostgreSQL驱动
执行命令:pip install psycopg2-binary修正代码,手动指定数组类型映射,修正连接逻辑
import datetime import pandas as pd from sqlalchemy import create_engine # 导入需要的数组类型和基础类型 from sqlalchemy.types import ARRAY, Boolean, String mock_data = {} mock_data['a'] = 'HELLO' mock_data['b'] = { 'c' : { 'd' : True, 'e' : [] }, 'f' : 'TESTING' } df = pd.json_normalize(mock_data) engine = create_engine("postgresql://postgres:ABCDEFG@localhost:5432/testing") table_name = 'testing-db' try: # 手动指定各列对应的数据类型,列表列用ARRAY包裹元素类型 dtype_map = { 'a': String(), 'b.c.d': Boolean(), 'b.c.e': ARRAY(String()), # 可根据实际存储的元素类型调整,比如ARRAY(Integer) 'b.f': String() } # 插入时指定dtype,同时开启事务提交 with engine.connect() as con: frame = df.to_sql(con=con, name=table_name, index=False, if_exists='replace', dtype=dtype_map) con.commit() print(frame) except ValueError as vx: print(vx) except Exception as ex: print(ex) else: print(f"Table {table_name} created successfully.")
补充说明
- 如果列表存储的是整数类型,将
ARRAY(String())替换为ARRAY(Integer())即可 - 使用
with上下文管理连接可以自动处理连接关闭,避免手动关闭时的变量错误 - 插入完成后必须执行
commit()提交事务,否则数据只会保存在临时事务中,不会真正写入数据库
内容的提问来源于stack exchange,提问作者Shazbots
相关产品推荐
相关产品推荐

