数据库加锁避免多线程访问报错

This commit is contained in:
shuaikangzhou
2023-11-17 21:34:22 +08:00
parent 142a260f01
commit fc0b1250c4
13 changed files with 574 additions and 111 deletions

View File

@@ -1,10 +1,12 @@
import os.path
import re
import sqlite3
import threading
DB = []
cursor = []
msg_root_path = "./app/Database/Msg/"
lock = threading.Lock()
# misc_path = './Msg/Misc.db'
if os.path.exists(msg_root_path):
for root, dirs, files in os.walk(msg_root_path):
@@ -54,18 +56,41 @@ def get_messages(username_):
return result
def get_message_by_num(username_, n):
sql = '''
select localId,TalkerId,Type,SubType,IsSender,CreateTime,Status,StrContent,strftime('%Y-%m-%d %H:%M:%S',CreateTime,'unixepoch','localtime') as StrTime
from MSG
where StrTalker=?
order by CreateTime
limit 10
'''
result = []
try:
lock.acquire(True)
for cur in cursor:
cur = cursor[-1]
cur.execute(sql, [username_])
result_ = cur.fetchall()
result += result_
return result_
finally:
lock.release()
result.sort(key=lambda x: x[5])
return result
def close():
for db in DB:
db.close()
if __name__ == '__main__':
from pprint import pprint
msg_root_path = './Msg/'
init_database()
username = 'wxid_0o18ef858vnu22'
result = get_messages(username)
pprint(result)
pprint(len(result))
# username = 'wxid_0o18ef858vnu22'
# result = get_messages(username)
# pprint(result)
# pprint(len(result))
result = get_message_by_num('wxid_0o18ef858vnu22', 0)
print(result)