. Preface Why do we need to mention the multithreading of SQLite? Because creating an SQLite connection can only be used by the thread that creates the connection. According to the general practice of the Connection Pool, several Conns are initialized and put into the pool. Obviously, this is not acceptable (other threads cannot use it ). If you use another method, the connection is created by the thread only when the connection is used for the first time, and then mapped to the thread and pushed to the pool, verify whether the connection is available before using the connection -- this is a good implementation.
Below is a simple implementation that does not involve pools ~~, There is time for implementation.
- first, define a class to operate on the addition of a test table in a database. delete. query and name it testdao. Oh, no! This name is too bloody.
Import threadingimport OS, sqlite3class Dao (object ): '''data persistence processing class''' def _ init _ (self, path, name = '', * ARGs, ** kwargs ): '''initialization... '''self. lock = threading. rlock () # Lock self. name = Name self. path = path # database connection parameter db_path = self. path [: Self. path. rfind (OS. SEP)] If OS. path. exists (db_path): OS. makedirs (db_path) def get_conn (Self): ''' creates a connection. Why cannot it be set as an instance member? Think about it, -- '''conn = sqlite3.connect (self. path) return conn def conn_close (self, Conn = none): '''after the operation is complete, turn off the connection ''' Conn. close () def save (self, OBJ, Conn = none): ''' save data ''' Cu = Conn. cursor () cu.exe cute (obj. to_insert_ SQL ()
- Define the interceptor related to the database connection.FuncConnect to the database before calling,FuncCall ends to increase the transaction and close the connection.
Def conn_trans (func): ''' interceptor related to database connection. connect to the database before the func call. The func call ends to increase the transaction and close the connection. '''def connection (self, * ARGs, ** kwargs): Self. lock. acquire () Conn = self. get_conn () kwargs ['conn'] = conn rs = func (self, * ARGs, ** kwargs) self. conn_close (conn) self. lock. release () Return Rs return connection
-
- Use the Interceptor to intercept the Save Method
@ Conn_trans () def save (self, OBJ, Conn = none): ''' save data ''' Cu = conn. cursor () cu.exe cute (obj. to_insert_ SQL ())