python sqlite3多线程访问的解决方案

要解决的问题:

sqlite3只支持的单线程访问,多个地方同时访问数据库造成datalock的报错。数据库在界面线程

 

解决方案:

1、对sqlite3采用访问,用完即关闭,解决创建线程和打开线程不一致。

2、对sqlite3的访问函数使用线程锁,以防止数据库datalock的错误

 

具体案例:

import threading

self.lock=threading.Lock() 

def Database_connect(self):
        print(time.time())

       self.lock.acquire()  #加锁
        self.conn = sqlite3.connect("code.db")
        self.cursor = self.conn.cursor()    

       ....................................

        self.conn.close()

        self.lock.release() #释放锁
        print(time.time())
        pass

        Thread_auto_1 = threading.Thread(target=self.Database_connect)
        Thread_auto_1.start()

 

 

 

你可能感兴趣的:(python,sqlite3)