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

如何用Python动态更新SQL数据库?插入代码未实际生效问题

解决MySQL数据插入后未更新的问题

你的问题出在事务未提交上。mysql.connector连接MySQL时默认开启事务模式,执行INSERT操作后,数据只是暂存到事务缓冲区,不会立刻写入数据库表。必须手动提交事务,才能让数据永久保存到数据库中。

解决方法

方法1:手动提交事务

在执行完execute语句后,调用连接对象的commit()方法:

import mysql.connector

db = mysql.connector.connect(host="localhost", user="1234", passwd="1234", database="books1")

mycursor = db.cursor()

label = '202'
position = 'A1'

sql2 = """INSERT INTO info (label, position) VALUES (%s, %s)"""  
db2 = (label, position)

mycursor.execute(sql2, db2)
# 添加事务提交语句
db.commit()

print("Updated")

方法2:开启自动提交

如果希望所有操作都自动提交,可以在建立数据库连接时添加autocommit=True参数:

import mysql.connector

# 连接时开启自动提交
db = mysql.connector.connect(
    host="localhost", 
    user="1234", 
    passwd="1234", 
    database="books1",
    autocommit=True
)

mycursor = db.cursor()

label = '202'
position = 'A1'

sql2 = """INSERT INTO info (label, position) VALUES (%s, %s)"""  
db2 = (label, position)

mycursor.execute(sql2, db2)

print("Updated")

两种方法都能解决数据未写入数据库的问题,根据实际需求选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:25:25