在线程计时器中运行SQL语句的Python
我试图每分钟运行一条SQL语句,但我需要能够不断地迭代传入的数据。因此,我制作了一个线程计时器,我在另一个So问题的帮助下找到了它,但在尝试运行它时,我收到了以下错误。有什么解决办法在线程计时器中运行SQL语句的Python,python,mysql,multithreading,timer,Python,Mysql,Multithreading,Timer,我试图每分钟运行一条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
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()
回答你的“为什么”问题。我认为这是因为您的连接在主线程上,而您对连接的提交在另一个线程上。希望这是正确的,我也希望这会有所帮助。将连接放在同一个线程中应该可以工作。如果你每分钟都这样做,我想没关系。不过,每秒建立一次连接似乎有点贵
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()
回答你的“为什么”问题。我认为这是因为您的连接在主线程上,而您对连接的提交在另一个线程上。希望这是正确的,我希望这有帮助。谢谢你,我昨晚试过了,但还是出现了同样的错误,我一定是在什么地方搞砸了。更新最多只能每分钟更新一次,很可能更少,所以应该不会有问题。谢谢你,我昨晚尝试过,但仍然出现相同的错误,我一定是在什么地方出了问题。更新最多只能每分钟更新一次,很可能更少,所以应该不会有问题。