Python在线程定时器中运行SQL语句

标签 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 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/

相关文章:

Python2.7 - 循环中的 list.remove(item) 给出了意外的行为

Python;读取文件并找到所需的文本

php - MySql 数据透视表到 Yii CActiveDataProvider

java - 我如何才能知道在我的操作系统上进行上下文切换需要多长时间?

Python 错误 : X() takes exactly 1 argument (8 given)

php - Laravel 应用上的 Locust 登录测试

mysql - 将 CAP_FIRST 函数从 MySQL 转换为 PostgreSQL

mysql 使用日期指示器对字母数字交易代码进行排序

java - 同步方法中的线程锁定

c# - Redis Pub/Sub ServiceStack,取消线程