python sqlite3 多线程_在python中多线程访问sqlite3数据库

Python标准库中有sqlite3模块,可见对此数据库的认可。不过,此模块在使用时也有限制,同一个数据库连接,不能在不同线程中共享。

import threading

import sqlite3

sqlite_mutex = threading.Lock()

db = sqlite3.connect('tdb2')

def initdb():

try:

db.executescript("""

create table stocks(id integer primary key, name text);

""")

except Exception as e:

print(repr(e))

def insertdb(name):

with sqlite_mutex:

try:

for i in range(100):

db.execute('insert into stocks values (%d,%s)'%(i,name))

except Exception as e:

print(repr(e))

initdb()

ths = []

for i in range(10):

th = threading.Thread(target=insertdb, args=(str(i),))

ths.append(th)

for i in range(10):

ths[i].start()

for i in range(10):

ths[i].

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python使用SQLite3数据库进行多线程操作时,需要注意以下几点: 1. 每个线程都应该创建自己的数据库连接对象,而不是共享同一个连接对象。因为SQLite3数据库不支持多线程共享同一个连接对象,这会导致数据混乱和操作失败。 2. 对于每个线程使用的数据库连接对象,应该使用`threading.local()`函数创建一个本地线程变量,以保证每个线程都可以独立使用自己的连接对象。 3. 为了避免多个线程同时访问同一个数据库文件导致的资源竞争问题,可以使用Python线程锁来控制数据库访问。 下面是一个简单的示例代码,演示了如何在多线程环境下使用SQLite3数据库: ``` import sqlite3 import threading # 创建本地线程变量 local = threading.local() # 线程锁 lock = threading.Lock() # 连接数据库 def connect_db(): conn = sqlite3.connect('test.db') local.conn = conn # 执行SQL语句 def execute_sql(sql): # 获取本地线程变量的连接对象 conn = local.conn # 如果连接对象不存在,则创建一个 if not conn: connect_db() conn = local.conn # 加锁 lock.acquire() try: cursor = conn.cursor() cursor.execute(sql) conn.commit() finally: # 释放锁 lock.release() # 多线程执行SQL语句 def worker(): execute_sql("INSERT INTO test VALUES ('test')") # 启动多个线程 threads = [] for i in range(10): t = threading.Thread(target=worker) threads.append(t) for t in threads: t.start() for t in threads: t.join() ``` 在上面的代码,我们使用了一个本地线程变量来存储每个线程数据库连接对象,这样每个线程都可以独立使用自己的连接对象,避免了多线程共享连接对象导致的问题。同时,使用了一个线程锁来控制数据库访问,避免了多个线程同时访问同一个数据库文件导致的资源竞争问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值