You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python DataFrame和SQLAlchemy创建MySQL表及报错解决

问题根因分析

  • con_engine 函数没有返回数据库引擎对象,调用后返回值为None,to_sql接收无效的连接参数时触发类型校验异常,是本次报错的核心原因
  • con_engine 存在语法缩进错误,url变量定义和def声明写在了同一行,没有正确缩进
  • 代码设置了index=False,但IdBien是索引名,索引默认不会被写入表中,dtype里多余声明了不存在的IdBien字段
  • 连接地址未指定目标数据库,to_sql无法识别需要写入的库位置

修复后可运行代码

import pandas as pd
from sqlalchemy import create_engine, Integer

header_Bien_Immo = ['LotNb']
df_Bien_Immo = df1.loc[:, header_Bien_Immo]
df_Bien_Immo['IdLot'] = IdLot
# 将索引转为普通列,保证IdBien可以写入表中
df_Bien_Immo = df_Bien_Immo.reset_index(names=['IdBien'])

def con_engine():
    # 连接地址指定目标数据库
    url = "mysql+pymysql://{user}:{password}@localhost/data_immo"
    engine = create_engine(url.format(user='root', password='Fer458it'))
    engine.execute("CREATE DATABASE IF NOT EXISTS data_immo")
    # 返回引擎对象给to_sql做连接参数
    return engine

def create_table(df):
    df.to_sql(
        name='bien_immo', 
        con=con_engine(), 
        if_exists='append', 
        index=False,
        dtype={
            'LotNb': Integer,
            'IdLot': Integer,
            'IdBien': Integer
        }
    )

create_table(df_Bien_Immo)

内容的提问来源于stack exchange,提问作者de Beyssac Olivier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:36:00