我试图每分钟运行一条 SQL 语句,但我也需要能够连续迭代传入的数据。因此,我在另一个 SO 问题的帮助下创建了一个线程计时器,但在尝试运行它时收到以下错误。对此有哪些解决方案?
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 18460 and this is thread id 29296
这是定时器代码的示例。我在这里每秒使用一次更新仅用于测试目的。
def update():
threading.Timer(1.0, update).start()
cursor.execute("UPDATE users SET timer = timer + 1")
db.commit()
print("Updating all timers")
update()
最佳答案
这应该通过将连接放在同一个线程中来工作。如果你每分钟都这样做,我想它没问题。不过,每秒建立一个连接似乎有点昂贵。
def update():
threading.Timer(1.0, update).start()
conn = sqlite3.connect(db)
cursor = conn.cursor()
cursor.execute("UPDATE users SET timer = timer + 1")
conn.commit()
print("Updating all timers")
update()
回答您的“为什么”问题。我认为这是因为您的连接在主线程上,而您对连接的提交在另一个线程上。希望这是正确的,我希望这会有所帮助。
关于Python在线程定时器中运行SQL语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501000/