【python下用sqlite3, 多线程下报错,原因和解决 】

在python下用sqlite3, 多线程 在UPDATE 或者INSERT的时候, 会报错

sqlite3.OperationalError: cannot commit - no transaction is active

1. 原因

多线程写冲突

  • 非原子写操作:如果多个线程同时执行非原子写操作,可能会导致数据覆盖或不一致。

2. 解决方案

使用锁

使用锁来确保同一时间只有一个线程可以执行写操作。

go 复制代码
import sqlite3
import threading

lock = threading.Lock()

def worker(conn, thread_id):
    with lock:
        cursor = conn.cursor()
        cursor.execute("INSERT INTO test (id, value) VALUES (?, ?)", (thread_id, f"value_{thread_id}"))
        conn.commit()
        cursor.close()

def main():
    conn = sqlite3.connect('example.db', check_same_thread=False)
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, value TEXT)")
    conn.commit()
    cursor.close()

    threads = []
    for i in range(5):
        thread = threading.Thread(target=worker, args=(conn, i))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    conn.close()

if __name__ == "__main__":
    main()

使用事务

显式事务管理:在每个线程中显式地开始和提交事务,确保事务的原子性和一致性。

go 复制代码
import sqlite3
import threading

def worker(conn, thread_id):
    cursor = conn.cursor()
    cursor.execute("BEGIN")
    cursor.execute("INSERT INTO test (id, value) VALUES (?, ?)", (thread_id, f"value_{thread_id}"))
    conn.commit()
    cursor.close()

def main():
    conn = sqlite3.connect('example.db', check_same_thread=False)
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, value TEXT)")
    conn.commit()
    cursor.close()

    threads = []
    for i in range(5):
        thread = threading.Thread(target=worker, args=(conn, i))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    conn.close()

if __name__ == "__main__":
    main()
相关推荐
数据智能老司机24 分钟前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i2 小时前
django中的FBV 和 CBV
python·django
c8i2 小时前
python中的闭包和装饰器
python
DemonAvenger5 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
这里有鱼汤5 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩15 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥16 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
该用户已不存在20 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
RestCloud21 小时前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python