· 5 years ago · Jul 12, 2020, 11:50 AM
1# blow!
2
3import sqlite3
4import time
5import threading
6
7
8class SQLiter:
9
10 def __init__(self, database):
11 self.database = database
12 self.lock = threading.Lock()
13
14 def execute(self, sql, values=[]):
15 with self.lock:
16 with sqlite3.connect(self.database) as conn:
17 conn.create_function("sleep", 1, time.sleep)
18 curr = conn.cursor()
19 curr.execute(sql, values)
20 #curr.execute("""select sleep(1)""")
21 conn.commit()
22
23 def select(self, sql, values=[]):
24 with self.lock:
25 with sqlite3.connect(self.database) as conn:
26 conn.create_function("sleep", 1, time.sleep)
27 curr = conn.cursor()
28 curr.execute(sql, values)
29 return curr.fetchall()
30
31if __name__ == '__main__':
32
33 sqliter = SQLiter('test.sqlite')
34 sqliter.execute(""" delete from test """)
35 sqliter.execute(""" create table if not exists test (id int) """)
36
37 sql = """ insert into test(id) values(?)"""
38 values = []
39 threads = []
40 t1 = time.monotonic()
41 for i in range(2):
42 values = (i, )
43 thread = threading.Thread(target=sqliter.execute, args=(sql, values))
44 threads.append(thread)
45 thread.start()
46 for thread in threads:
47 thread.join()
48 t2 = time.monotonic()
49
50 res = sqliter.select(""" select id from test order by id desc """)
51 print(res)
52
53 print('done in %.6f seconds' % (t2-t1))