Python SQLite3中如何获取并打印更新行的Row ID
这问题我熟!要获取UPDATE操作影响的行的Row ID,其实有两种靠谱的方法,取决于你用的SQLite版本,我给你拆解一下:
方法1:兼容所有SQLite版本(先查询再更新)
这种方法适配所有版本的SQLite,核心思路是先把符合更新条件的行ID查出来,再执行更新,这样就能精准拿到被修改的那些ID。而且一定要用事务包裹,避免查询和更新之间有其他操作篡改数据。
修改后的代码如下:
import sqlite3 # 把数据库连接放在循环外面,不用每次都创建销毁,大幅提升效率 conn = sqlite3.connect('database.db', timeout=60) cursor = conn.cursor() try: while True: # 先查询符合条件的行ID,用FOR UPDATE锁定行,防止并发场景下数据被篡改 cursor.execute("SELECT rowid FROM row WHERE status='status' FOR UPDATE") updated_row_ids = [row[0] for row in cursor.fetchall()] if updated_row_ids: # 用参数化查询执行更新,避免SQL注入风险 placeholders = ','.join('?' for _ in updated_row_ids) cursor.execute(f"UPDATE row SET value='value' WHERE rowid IN ({placeholders})", updated_row_ids) # 打印被更新的Row ID print(f"Updated row IDs: {updated_row_ids}") conn.commit() else: # 没有符合条件的行时,加个延迟避免空循环占用过多资源 import time time.sleep(1) conn.commit() except KeyboardInterrupt: print("Stopping the loop...") finally: # 确保程序退出时关闭数据库连接 conn.close()
方法2:用SQLite的RETURNING子句(简洁高效,需SQLite 3.35.0+)
如果你的SQLite版本在3.35.0或以上(可以用sqlite3.sqlite_version查看当前版本),那直接用RETURNING子句就能在UPDATE后直接返回被修改的行ID,一步到位,代码更简洁:
import sqlite3 # 先确认当前SQLite版本是否支持RETURNING print(f"SQLite version: {sqlite3.sqlite_version}") conn = sqlite3.connect('database.db', timeout=60) cursor = conn.cursor() try: while True: # 执行UPDATE的同时返回被修改的rowid cursor.execute("UPDATE row SET value='value' WHERE status='status' RETURNING rowid") updated_row_ids = [row[0] for row in cursor.fetchall()] if updated_row_ids: print(f"Updated row IDs: {updated_row_ids}") else: import time time.sleep(1) conn.commit() except KeyboardInterrupt: print("Stopping the loop...") finally: conn.close()
另外提一句:你原来的代码每次循环都创建新连接再关闭,会有不小的性能损耗,上面的示例都把连接放在了循环外部,用try-finally确保连接最终关闭,这是更规范的写法~
内容的提问来源于stack exchange,提问作者ebo ahmad
相关产品推荐
相关产品推荐

