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

使用Pandas向MySQL插入数据仅生成表结构,无数据行插入的问题排查

解决pandas to_sql仅创建表但不插入数据的问题

你的代码核心问题是事务未提交,再加上连接管理不当,导致数据没有真正写入数据库。以下是具体原因和解决办法:

核心原因

SQLAlchemy的Connection实例默认开启事务机制,to_sql执行后不会自动提交事务,所有插入操作都停留在内存的事务中,没有持久化到数据库。同时你的Database类返回的是手动创建的Connection对象,没有处理事务提交逻辑。

解决办法

办法1:手动提交事务

在执行to_sql后,手动调用连接的commit()方法提交事务,最后关闭连接:

frame.to_sql('ds_attribution_probabilities', con=db_connection, 
             index=False, if_exists='append')
db_connection.commit()  # 提交事务
db_connection.close()   # 关闭连接释放资源

办法2:用上下文管理器自动管理事务(推荐)

改用SQLAlchemy的引擎上下文管理器,它会自动处理事务的提交和回滚,无需手动操作:
先修改你的Database类,让它返回引擎而非直接连接:

class Database:
    def __init__(self, host, user, password, database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.engine = None

    def get_engine(self):
        try:
            if not self.engine:
                self.engine = create_engine(f'mysql+mysqlconnector://{self.user}:{self.password}@{self.host}/{self.database}')
                print("Connected to the database.")
            return self.engine
        except Exception as e:
            print(f"Error: {e}")

然后用上下文管理器执行插入:

db_instance = Database(host='localhost', user='root', password='', database='test2')
engine = db_instance.get_engine()

# 上下文自动处理事务提交
with engine.begin() as conn:
    frame.to_sql('ds_attribution_probabilities', con=conn, 
                 index=False, if_exists='append')

其他排查点

  • 检查class字段:虽然MySQL中class是关键字,但pandas会自动用反引号包裹字段名,一般不会有问题,若仍报错可修改字段名(比如改为label)。
  • 确认数据类型匹配:你的DataFrame中feature1/feature2是浮点型,class是整型,MySQL会自动映射为FLOAT和INT类型,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:52:42