【问题标题】:SQL INSERT in SQLITE with APSCHEDULER使用 APSCHEDULER 在 SQLITE 中插入 SQL
【发布时间】:2017-12-11 22:31:33
【问题描述】:

从在 apscheduler 中运行的作业中在 sqlite3 中插入​​值时遇到问题。

我正在寻找一种从作业中插入值的方法。我想这意味着从主机线程运行作业?或者填充缓冲区并将其汇集到管理 sql 事务的单个线程?

处理此问题的最佳方法是什么?我计划稍后在烧瓶应用程序中运行它。

代码如下:

"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())

def tick1():
    print('Tick1! The time is: %s' % datetime.now())
    id = "testId"
    global sql_cursor
    sql_cursor.execute("INSERT INTO histories VALUES(?,?,?)", (datetime.now(),id,0.0))


if __name__ == '__main__':
    import sqlite3
    sql_db = sqlite3.connect('histories.db')
    sql_cursor = sql_db.cursor()
    sql_cursor.execute(
    '''CREATE TABLE IF NOT EXISTS histories(
       timestamp DATE, id TEXT, value REAL)''')
    sql_db.commit()

    scheduler = BackgroundScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    scheduler.add_job(tick1, 'interval', seconds=1)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()

还有错误:

    Tick1! The time is: 2017-12-11 22:22:59.232296
    Job "tick1 (trigger: interval[0:00:01], next run at: 2017-12-11 22:22:59 UTC)" raised an exception
    Traceback (most recent call last):
      File "/usr/local/lib/python3.5/dist-packages/apscheduler/executors/base.py", line 125, in run_job
        retval = job.func(*job.args, **job.kwargs)
      File "background.py", line 20, in tick1
        sql_cursor.execute("INSERT INTO histories VALUES(?,?,?)", (datetime.now(),id,0.0))
    sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id -1225585456 and this is thread id -1260391312

【问题讨论】:

  • 为什么要使用在另一个线程中创建的游标对象?您是否尝试在您真正需要的地方创建连接(=tick1)?当然也可以在同一个地方提交
  • 我现在就试试这个。连续快速连接和创建光标有问题吗?

标签: python python-3.x flask sqlite apscheduler


【解决方案1】:

连接和游标不能轻易地跨线程使用。为了在评论中回答您的问题,只要您在使用结束时执行 connection.close() ,快速连续创建连接就不会有任何问题。 下面的示例应该让您对它的外观有一个很好的了解。您可以通过创建自己的类来连接和执行来整理它。

import os
from apscheduler.schedulers.background import BackgroundScheduler
def tick():
    print('Tick! The time is: %s' % datetime.now())

def tick1():
    print('Tick1! The time is: %s' % datetime.now())
    id = "testId"
    sql_db = sqlite3.connect('histories.db')
    sql_cursor = sql_db.cursor()
    sql_cursor.execute("INSERT INTO histories VALUES(?,?,?)", (datetime.now(),id,0.0))
    sql_cursor.close()
    sql_db.close()


if __name__ == '__main__':
    import sqlite3
    sql_db = sqlite3.connect('histories.db')
    sql_cursor = sql_db.cursor()
    sql_cursor.execute(
    '''CREATE TABLE IF NOT EXISTS histories(
       timestamp DATE, id TEXT, value REAL)''')
    sql_db.commit()
    sql_cursor.close()
    sql_db.close()
    scheduler = BackgroundScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    scheduler.add_job(tick1, 'interval', seconds=1)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2014-02-12
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多