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

Python使用mysql-connector-python无法向MySQL数据库写入数据问题求助

问题原因

mysql-connector-python 默认关闭自动事务提交,你执行INSERT这类DML语句后没有提交事务,连接断开后操作会被自动回滚,因此数据不会写入数据库。而直接在数据库命令行执行语句时,大多数环境默认开启了自动提交,因此可以正常写入。

解决方法

方案1:执行完操作后手动提交事务(推荐,方便事务控制)

在执行完INSERT语句后新增cnx.commit()即可:

cnx = mysql.connector.connect(user="root", database="my_db")
cursor = cnx.cursor()

# 执行插入语句
cursor.execute("INSERT INTO category (category_name) VALUES ('test')")
# 手动提交事务
cnx.commit()

cursor.close()
cnx.close()

如果执行过程中捕获到异常,可以调用cnx.rollback()回滚未提交的操作,保证数据一致性。

方案2:连接时开启自动提交

如果不需要手动控制事务,可以在建立连接时添加autocommit=True参数,所有操作执行后会自动提交:

# 开启自动提交
cnx = mysql.connector.connect(user="root", database="my_db", autocommit=True)
cursor = cnx.cursor()

cursor.execute("INSERT INTO category (category_name) VALUES ('test')")
# 无需再手动调用commit

cursor.close()
cnx.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:51:03