在PyCharm中使用SQL更新数据库行无效,如何解决?
解决数据库更新后数据未生效的问题
你遇到的核心问题大概率是事务没有提交——很多数据库(比如SQLite、MySQL)默认不会自动提交修改,执行完UPDATE后必须手动确认,否则所有变更都会回滚。
给你几个针对性的修复和检查步骤:
1. 必须添加事务提交
你的代码只执行了execute,但没提交事务。可以通过游标获取连接对象来提交:
def update_row(db_cursor): sql = "update patient_profile set zip_code = ?, no_shows = ? where occupation = ?" occupation = input("Enter the occupation (str) for your patient profile you would like to update: ") zip_code = int(input("Enter your new zipcode (int) : ")) no_shows = int(input("Enter a new number for how many times you think you have no-showed (int): ")) tuple_of_values = (zip_code, no_shows, occupation) db_cursor.execute(sql, tuple_of_values) # 新增:提交事务,让修改生效 db_cursor.connection.commit() print("Row updated.")
如果你的函数能直接拿到数据库连接对象(比如db_conn),也可以直接调用db_conn.commit(),效果完全一致。
2. 检查是否真的匹配到了目标行
有时候代码逻辑没问题,但WHERE条件根本没命中任何行。可以在执行后打印受影响的行数,确认是否有行被修改:
db_cursor.execute(sql, tuple_of_values) print(f"实际更新了{db_cursor.rowcount}行") db_cursor.connection.commit()
如果输出是0,说明你输入的occupation和数据库里的记录不匹配——注意大小写、空格(比如数据库里是"Doctor",你输入"doctor"就会不匹配),或者这个职业的记录根本不存在。
3. 排查数据类型和SQL错误
- 确认数据库里
zip_code、no_shows的字段类型和你输入的一致(比如都是整数),如果数据库里zip_code是字符串类型,你强行转成int就会出错。 - 可以加个异常捕获,看看执行时有没有隐藏报错:
try: db_cursor.execute(sql, tuple_of_values) db_cursor.connection.commit() print(f"实际更新了{db_cursor.rowcount}行") except Exception as e: print(f"更新出错:{e}")
先按第一步加提交试试,这是新手操作数据库最容易踩的坑。
内容的提问来源于stack exchange,提问作者Lara Castro
相关产品推荐
相关产品推荐

