解决方案: 始终关闭cursor
for(甚至只读)查询!
首先,这是重现问题的一种方法:
- 第一次运行此代码,一次:
import sqlite3 conn = sqlite3.connect('anothertest.db') conn.execute("CREATE TABLE IF NOT EXISTS mytable (id int, description text)") for i in range(100): conn.execute("INSERT INTO mytable VALUES(%i, 'hello')" % i) conn.commit()初始化测试。
- 然后开始一个 只读 查询:
import sqlite3, time conn = sqlite3.connect('anothertest.db') c = conn.cursor() c.execute('SELECt * FROM mytable') item = c.fetchone() print(item) print('Sleeping 60 seconds but the cursor is not closed...') time.sleep(60)并 在执行下一步时 保持此脚本运行:
- 然后尝试删除一些内容并提交:
import sqlite3 conn = sqlite3.connect('anothertest.db') conn.execute("DELETe FROM mytable WHERe id > 90") conn.commit()确实会触发此错误:
sqlite3.OperationalError:数据库已锁定
为什么?因为无法删除读取查询当前正在访问的数据:如果游标仍处于打开状态,则意味着仍可以使用
fetchone或来获取数据
fetchall。
解决错误的方法如下:在步骤2中,只需添加:
item = c.fetchone() print(item) c.close() time.sleep(60)
然后,在此脚本仍在运行时,启动脚本#3,您将看到没有更多错误。



