【问题标题】:How to share database over different threads in python如何在python中的不同线程上共享数据库
【发布时间】:2019-05-28 23:31:47
【问题描述】:

我目前正在从事一个需要在 python 中通过不同线程共享数据库的项目。我目前正在使用 sqlite3 和 python3.7。

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

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

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

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

【问题讨论】:

    标签: database python-3.x multithreading sqlite


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多