You need to enable JavaScript to run this app. Python向phpMyAdmin MySQL库写入DataFrame数据失败的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Python向phpMyAdmin MySQL库写入DataFrame数据失败的问题排查

Pandas DataFrame 写入本地 MySQL 数据库问题排查

复现流程

数据库侧准备

先执行如下SQL完成库表创建:

CREATE SCHEMA IF NOT EXISTS `proyecto` DEFAULT CHARACTER SET utf8 ;
USE `proyecto`;
CREATE TABLE IF NOT EXISTS `pueblos`(
    `Pueblo` VARCHAR(60) NOT NULL,
    `Comunidad` VARCHAR(60) NOT NULL,
    `Provincia` VARCHAR(60) NOT NULL,
    `Latitud` float NOT NULL,
    `Longitud` float NOT NULL,
    `Altitud` float NOT NULL,
    `Habitantes` int NOT NULL,
    `Hombres` int NOT NULL,
    `Mujeres` int NOT NULL,
  PRIMARY KEY (`Pueblo`))
ENGINE = InnoDB;

Python 环境配置

导入依赖库的代码:

import numpy as np
import pandas as pd
import MySQLdb
# 若缺少mysqlclient需提前执行 pip install mysqlclient

数据读取与预处理

df= pd.read_excel('https://www.businessintelligence.info/resources/assets/listado-longitud-latitud-municipios-espana.xls')
df=df.drop(index = 0)
new_header = df.iloc[0] 
df= df[1:] 
df.columns = new_header 

基础连接验证

测试插入语句执行成功,可正常看到插入数据,证明数据库连接、基础插入逻辑无问题:

db=MySQLdb.connect("localhost","root","","proyecto")
insertrec=db.cursor()
a="se"
b="ha"
c="insertado"
sqlquery="INSERT INTO Pueblos (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres) VALUES('"+a+"', '"+b+"','"+c+"',7,8,9,10,11,12)"

insertrec.execute(sqlquery)
db.commit()
print("Success!!")
db.close()

尝试执行的错误操作

  1. 逐行循环插入失败
# 原代码存在缩进错误、SQL拼接错误、连接关闭逻辑错误
for index, row in df.iterrows():
Pueblo=row['Población']
Comunidad=row['Comunidad']
Provincia=row['Provincia']
Latitud=row['Latitud']
Longitud=row['Longitud']
Altitud=row['Altitud']
Habitantes=row['Habitantes']
Hombres=row['Hombres']
Mujeres=row['Mujeres']

# SQL语句未拼接变量,直接将row字典表达式写入字符串
sqlquery="INSERT INTO Pueblos (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres) VALUES(row['Población'], row['Comunidad'],row['Provincia'], row['Latitud'],row['Longitud'],row['Altitud'],row['Habitantes'],row['Hombres'],row['Mujeres'])"
insertrec.execute(sqlquery)
db.commit() 
# 连接写在循环内部,首次执行完就关闭连接
db.close()
  1. 直接用原生连接执行df.to_sql失败
# 旧版pandas不支持直接传入MySQLdb原生连接,需使用SQLAlchemy引擎
df.to_sql("pueblos",db,if_exists='append',index=False)
  1. 改用SQLAlchemy引擎执行写入仍报 OperationalError: (MySQLdb._exceptions.OperationalError) (1054,NULL) 错误
from sqlalchemy import create_engine
engine = create_engine("mysql://ana:ana@localhost/proyecto")
con = engine.connect()
df.to_sql(name='pueblos',con=con,if_exists='append')
con.close()

错误原因定位

  • 逐行插入失败原因
    • 循环体未加缩进,所有变量赋值、SQL执行逻辑都在循环外
    • SQL字符串拼接完全错误:没有将提取的变量拼入SQL语句,直接把row['xxx']的文本写入SQL,数据库无法识别
    • 数据库连接db.close()写在循环内部,首次提交后就关闭连接,后续执行直接报错
    • 字符串拼接方式存在SQL注入风险,未对特殊字符做转义
  • 原生连接执行to_sql失败原因
    • 旧版pandas的to_sql接口不兼容MySQLdb原生连接,要求传入SQLAlchemy引擎生成的连接对象
  • SQLAlchemy执行写入报1054错误原因
    • 列名不匹配:DataFrame中市镇列名为Población,但数据库表对应列名为Pueblo,to_sql默认按列名匹配字段,找不到对应列就抛出1054(未知列)错误
    • 未设置index=False:默认将DataFrame的索引作为额外列写入,与表结构冲突
    • 提前新增的int索引列与DataFrame默认写入的索引类型、名称不匹配
    • 预处理后的DataFrame存在空值、数据类型不匹配问题,导致非空字段插入NULL值触发约束报错

可行解决方案

方案1:修正逐行插入逻辑(仅适合小批量数据)

# 先打开连接,不要放在循环内
db=MySQLdb.connect("localhost","root","","proyecto")
insertrec=db.cursor()
for index, row in df.iterrows():
    # 所有循环内逻辑加缩进
    Pueblo=row['Población']
    Comunidad=row['Comunidad']
    Provincia=row['Provincia']
    Latitud=row['Latitud']
    Longitud=row['Longitud']
    Altitud=row['Altitud']
    Habitantes=row['Habitantes']
    Hombres=row['Hombres']
    Mujeres=row['Mujeres']
    # 使用参数化查询,避免拼接错误和注入风险
    sqlquery="INSERT INTO Pueblos (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres) VALUES(%s, %s,%s, %s,%s,%s,%s,%s,%s)"
    insertrec.execute(sqlquery, (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres))
# 所有循环执行完再提交、关闭连接
db.commit() 
db.close()

方案2:使用SQLAlchemy批量写入(推荐,性能更高)

  1. 先修正DataFrame列名、清洗异常数据,与数据库表规则完全匹配:
# 把Población列重命名为Pueblo,和数据库表列名一致
df = df.rename(columns={'Población': 'Pueblo'})
# 清除空值,避免非空约束报错
df = df.dropna()
# 转换数值列类型,避免类型不匹配
for col in ['Latitud','Longitud','Altitud','Habitantes','Hombres','Mujeres']:
    df[col] = pd.to_numeric(df[col], errors='coerce')
df = df.dropna()
  1. 移除之前给pueblos表新增的多余int索引列,使用匹配的连接执行写入:
from sqlalchemy import create_engine
# 连接字符串指定字符集,避免中文乱码
engine = create_engine("mysql+mysqldb://ana:ana@localhost/proyecto?charset=utf8")
con = engine.connect()
# 设置index=False,不写入DataFrame自带索引
df.to_sql(name='pueblos',con=con,if_exists='append', index=False)
con.close()

内容的提问来源于stack exchange,提问作者Ana Uribe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 12:36:02