python sqlite并发处理_Pythonsqlite3和并发

数据库锁定错误最可能的原因是您必须执行

conn.commit()

数据库操作完成后。否则, 数据库将被写锁定并保持不变。等待写入的其余线程将在一段时间后断开连接(默认值为5秒, 有关详细信息, 请参见

http://docs.python.org/2/library/sqlite3.html#sqlite3.connect

关于它)。

正确且同时插入的示例如下:

import threading, sqlite3

class InsertionThread(threading.Thread):

def __init__(self, number):

super(InsertionThread, self).__init__()

self.number = number

def run(self):

conn = sqlite3.connect('yourdb.db', timeout=5)

conn.execute('CREATE TABLE IF NOT EXISTS threadcount (threadnum, count);')

conn.commit()

for i in range(1000):

conn.execute("INSERT INTO threadcount VALUES (?, ?);", (self.number, i))

conn.commit()

# create as many of these as you wish

# but be careful to set the timeout value appropriately: thread switching in

# python takes some time

for i in range(2):

t = InsertionThread(i)

t.start()

如果您喜欢SQLite或拥有可用于SQLite数据库的其他工具, 或者想用SQLitedb文件替换CSV文件, 或者需要执行诸如跨平台IPC之类的罕见任务, 那么SQLite是一个很好的工具, 非常适合这个目标。如果对您不起作用, 请不要强行使用其他解决方案!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值