使用sqlite3包在python中的不同线程之间共享:内存:数据库 [英] sharing a :memory: database between different threads in python using sqlite3 package

查看:26
本文介绍了使用sqlite3包在python中的不同线程之间共享:内存:数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中创建一个 :memory: 数据库并从不同的线程访问它.基本上是这样的:

I would like to create a :memory: database in python and access it from different threads. Essentially something like:

class T(threading.Thread):
    def run(self):
        self.conn = sqlite3.connect(':memory:')
        # do stuff with the database

for i in xrange(N):
    T().start()

并且所有连接都指向同一个数据库.

and have all the connections referring to the same database.

我知道将 check_same_thread=True 传递给连接函数并共享线程之间的连接,但希望尽可能避免这样做.感谢您的帮助.

I am aware of passing check_same_thread=True to the connect function and sharing the connection between threads but would like to avoid doing that if possible. Thanks for any help.

更正了一个错字.我最初说让所有连接都指向同一个线程"用线程代替数据库.

corrected a typo. I originally said "have all the connections referring to the same thread" substituting thread for database.

推荐答案

如果不破解 sqlite3 库本身,您就无法重用 :memory: 数据库,因为它保证对每个连接都是独占和私有的.要破解它,请仔细查看 sqlite3 发行版(不是 Python 模块发行版)中的 src/pager.c.也许,最方便的实现方法是让 :memory:00, :memory:something, :memory:okay_hai 等别名到通过一些简单的 C 端映射处理不同的 pPager->memDb 指针.

Without hacking sqlite3 library itself you cannot reuse :memory: database, because it's guaranteed to be exclusive and private for every connection. To hack access to it, look closer at src/pager.c in sqlite3 distribution (not Python module distribution). Maybe, most convenient way to implement this would be make :memory:00, :memory:something, :memory:okay_hai etc. aliases to address different pPager->memDb pointers through some simple C-side mapping.

这篇关于使用sqlite3包在python中的不同线程之间共享:内存:数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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