首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中实现跨线程共享数据库

如何在python中实现跨线程共享数据库
EN

Stack Overflow用户
提问于 2019-01-02 17:58:35
回答 1查看 462关注 0票数 0

我目前正在做一个项目,需要在python中通过不同的线程共享数据库。我目前使用的是带有python3.7的sqlite3。

下面的代码是一个类似于我遇到的问题

代码语言:javascript
复制
import threading, os, sqlite3

os.chdir("/home/aditya/Desktop")

connection = sqlite3.connect("Name.db") # I am not using  :memory: because I need something permanent
cursor = connection.cursor()
cursor.execute("create table if not exists Name (names varchar)")
cursor.execute("insert into Name values('Some_Name')")
print("result from original database", end = "\t")
result = cursor.execute("select * from Name")
print(result.fetchall())

def return_cursor():
    conn = sqlite3.connect("Name.db")
    cur = conn.cursor()
    return cur


def DB_thread_one(): 

    print("result from thread 1", end = "\t")
    cur = return_cursor()
    result = cur.execute("select * from Name")
    print(result.fetchall()) # THIS RETURNS  AN EMPTY LIST

def DB_thread_two(): 

    print("result from thread 1", end = "\t")
    cur = return_cursor()
    result = cur.execute("select * from Name")
    print(result.fetchall()) # THIS RETURNS  AN EMPTY LIST

if __name__ == "__main__": 
    # creating thread 

    t1 = threading.Thread(target=DB_thread_one) 

    t2 = threading.Thread(target=DB_thread_two) 

    # starting thread 1 
    t1.start() 
    # starting thread 2 
    t2.start() 
    # wait until thread 1 is completely executed 
    t1.join() 
    # wait until thread 2 is completely executed 
    t2.join() 

    # both threads completely executed 
    print("Done!") 

我在谷歌上搜索了一些解决方案,发现了一个名为shared-cache的东西,并试图使用cache = shared启用它,但它不起作用,因为sqlite3.connect没有任何参数cache

我还读到SQLite不鼓励跨不同线程共享数据库连接,但是this link说python现在支持跨线程共享数据库连接。

我错过了什么?有没有更好的sqlite3替代方案,允许通过线程共享数据库(sqlalchemy?)

EN

回答 1

Stack Overflow用户

发布于 2019-01-02 23:34:47

当两个线程共享一个连接时,它们也共享事务。这可能会破坏程序的逻辑。

只需使用两个连接,每个线程一个。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54004294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档