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

Python的MySQLdb无法插入数据:代码无报错但表仍为空

问题解决:MySQL数据插入不生效但无报错

代码中的核心问题及修复方案:

  • 未初始化游标对象
    代码直接调用cursor.execute()但从未创建游标实例,必须在数据库连接后添加游标初始化代码:

    cursor = db.cursor()
    
  • SELECT结果判断逻辑错误
    cursor.execute()执行查询后返回的是匹配的行数,空表时返回0而非None,原判断条件永远不会触发,需修改为:

    x = cursor.execute("SELECT * from MasterPass ")
    if x == 0:
        print("nope")
        welcome_new_user()
    
  • 建议显式提交数据
    尽管连接时设置了autocommit=True,但部分MySQL环境下仍需显式提交才能确保数据写入,在插入语句后添加:

    db.commit()
    

修复后的完整代码:

import MySQLdb

db = MySQLdb.connect(host="localhost", 
   user="user", 
   passwd="pass", 
   db="database",
   autocommit=True) 
cursor = db.cursor()  # 初始化游标

def welcome_new_user():
    pass1 = input("Enter your master password")
    pass2 = input("Enter your master password again")
    if pass1 == pass2:
        cursor.execute("INSERT INTO MasterPass(masterpassword) VALUES (%s)", [pass1])
        print("pass added")
        db.commit()  # 显式提交确保数据写入
    else:
        print("Passwords don't match")
     
x = cursor.execute("SELECT * from MasterPass ")
if x == 0:
    print("nope")
    welcome_new_user()

db.close()  # 关闭数据库连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:10:54