Python sqlite3 和并发 [英] Python sqlite3 and concurrency

查看:81
本文介绍了Python sqlite3 和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用线程"模块的 Python 程序.每秒一次,我的程序启动一个新线程,从网络获取一些数据,并将这些数据存储到我的硬盘驱动器.我想使用 sqlite3 来存储这些结果,但我无法让它工作.问题似乎与以下行有关:

I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:

conn = sqlite3.connect("mydatabase.db")

  • 如果我将这行代码放在每个线程中,我会收到一个 OperationalError,告诉我数据库文件已锁定.我想这意味着另一个线程通过 sqlite3 连接打开了 mydatabase.db 并锁定了它.
  • 如果我把这行代码放在主程序中,并将连接对象(conn)传递给每个线程,我会得到一个ProgrammingError,说在一个线程中创建的SQLite对象只能在同一个线程中使用.
  • 立>

    以前我将所有结果存储在 CSV 文件中,并且没有任何这些文件锁定问题.希望这可以通过 sqlite 实现.有什么想法吗?

    Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?

    推荐答案

    您可以使用消费者-生产者模式.例如,您可以创建在线程之间共享的队列.从 Web 获取数据的第一个线程将这些数据排入共享队列.另一个拥有数据库连接的线程从队列中取出数据并将其传递给数据库.

    You can use consumer-producer pattern. For example you can create queue that is shared between threads. First thread that fetches data from the web enqueues this data in the shared queue. Another thread that owns database connection dequeues data from the queue and passes it to the database.

    这篇关于Python sqlite3 和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆