python多线程访问sqlite3_python操作sqlite示例(支持多进程/线程同时操作) - 学步园...

本文介绍了一种使用Python实现的多线程并发访问SQLite3数据库的方法,通过内部请求队列确保线程安全。示例中创建了一个SqliteMultithread类,允许在多个线程中并发执行SQL请求,同时支持事务处理和自动提交。
摘要由CSDN通过智能技术生成

import sqlite3fromQueue import Queuefromthreading import ThreadclassSqliteMultithread(Thread):''' Wrap sqlite connection in a way that allows concurrent requests frommultiple threads. Thisisdone by internally queueing the requests and processing them sequentiallyin a separate thread (inthe same order they arrived).'''def __init__(self, filename, autocommit, journal_mode): super(SqliteMultithread, self).__init__() self.filename=filename self.autocommit=autocommit self.journal_mode=journal_mode self.reqs=Queue() # use request queue of unlimited size self.setDaemon(True) # python2.5-compatible self.start() def run(self):ifself.autocommit: conn= sqlite3.connect(self.filename, isolation_level=None, check_same_thread=False)else: conn= sqlite3.connect(self.filename, check_same_thread=False) conn.execute('PRAGMA journal_mode = %s' %self.journal_mode) conn.text_factory=str cursor=conn.cursor() cursor.execute('PRAGMA synchronous=OFF')whileTrue: req, arg, res= self.reqs.get()if req == '--close--':breakelif req== '--commit--': conn.commit()else: cursor.execute(req, arg)ifres:for rec incursor: res.put(rec) res.put('--no more--')ifself.autocommit: conn.commit() conn.close() def execute(self, req, arg=None, res=None):''' `execute` calls are non-blocking: just queue up the request and returnimmediately.'''self.reqs.put((req, arg or tuple(), res)) def executemany(self, req, items):for item initems: self.execute(req, item) defselect(self, req, arg=None):''' Unlike sqlite's native select, this select doesn't handle iteration efficiently. The result of `select` starts filling up with values as soon asthe requestisdequeued, and although you can iterate over the result normally (`for res in self.select(): ...`), the entire result will be inmemory.''' res = Queue() # results of the select will appear as items in thisqueue self.execute(req, arg, res)whileTrue: rec= res.get()if rec == '--no more--':break yieldrec def select_one(self, req, arg=None):'''Return only the first row of the SELECT, or None if there are no matching rows.''' try:return iter(self.select(req, arg)).next() except StopIteration:returnNone def commit(self): self.execute('--commit--') def close(self): self.execute('--close--')#endclass SqliteMultithread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值