跨多个线程使用 sql Python

Using sql across multiple threads Python

我有一个服务器允许(管理员)创建、删除或编辑其他用户的详细信息, 我在函数内创建了数据库及其游标:

def DBSetup():
    global schoolDBConn, schoolDBCursor
    print("Setting up databases")
    schoolDBConn = sqlite3.connect("SCHOOL_DB.db")
    schoolDBCursor = schoolDBConn.cursor()
    schoolDBCursor.execute(
                            """
                               CREATE TABLE IF NOT EXISTS USER_DETAILS 
                               (
                               username text,
                               password text,
                               clearance int,
                               classes int
                               )
                            """
                            )
    schoolDBCursor.execute(   #line 300
                            """
                            CREATE TABLE IF NOT EXISTS CLASSES  
                            (
                            className text,
                            supervisor text,
                            assignmentName text
                            )
                            """
                            )
    schoolDBCursor.execute(
                            """
                            CREATE TABLE IF NOT EXISTS ASSIGNMENT 
                            (
                            setDate text,
                            dueDate text,
                            assignmentInfo text,
                            supervisor text
                            )  
                            """
                             )

我在服务器启动时调用它,然后开始我的线程:

if __name__ == "__main__":
    DBSetup()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host, port))
    s.listen(1)
    while True:
        conn, addr = s.accept()
        connThread = Thread(target=handler, args=(conn, addr))
        connThread.daemon = True
        connThread.start()

但是在我的线程中,每当我使用编辑数据库的函数时,我都会收到此错误:

SQLITE3 ERROR:

SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9628 and this is thread id 12400

每当我编辑数据库时,我都在我的程序中使用全局锁"With global_lock:"。

提前致谢

您可以将 check_same_thread 参数设置为 false。在你的情况下是这样的:

schoolDBConn = sqlite3.connect("SCHOOL_DB.db", check_same_thread=False)

来自文档:

By default, check_same_thread is True and only the creating thread may use the connection. If set False, the returned connection may be shared across multiple threads. When using multiple threads with the same connection writing operations should be serialized by the user to avoid data corruption.