在多线程中使用sqlite3

using sqlite3 in multithreading

我正在为许多客户端编写服务器程序,并且我使用了线程。 每个客户端都可以执行需要写入或读取 sqlite 数据库的操作。 我是否需要为每个操作打开和关闭连接或打开一次数据库以便所有客户端共享一个连接? 我的代码示例:

    if command == "s":
        conn = open_database() #connect to the database
        cursor = conn.cursor()
        cursor.execute('''SELECT s FROM users WHERE username=?''', (username,))
        s= cursor.fetchone()[0]
        conn.close()
        if not s:
            s= "Empty!"
        clientsock.send(str(s))

我也对数据库使用了插入命令。

一个连接只有一个事务,因此当多个线程尝试共享同一个连接而不锁定所有事务时,您的程序可能会崩溃。

每个线程使用一个连接。

(如果需要高并发,SQLitemight not be the best choice。)