添加对SQLite3数据库的支持

This commit is contained in:
Kakune55 2023-12-14 10:56:16 +08:00
parent 31aa97deca
commit 7b66cbb7e4
3 changed files with 92 additions and 40 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/__pycache__ /__pycache__
*.json *.json
APPData.db

View File

@ -3,3 +3,17 @@ import json
def readConf(): def readConf():
with open('config.json') as f: with open('config.json') as f:
return json.load(f) return json.load(f)
def updateConf(data_dict):
# 打开JSON文件并读取内容
file_path = 'config.json'
with open(file_path, 'r') as json_file:
existing_data = json.load(json_file)
# 将新的数据合并到现有的数据中
existing_data.update(data_dict)
# 再次打开文件(这次是以写模式),并将更新后的数据保存回文件
with open(file_path, 'w') as json_file:
json.dump(existing_data, json_file, indent=4, ensure_ascii=False)

115
db.py
View File

@ -1,29 +1,62 @@
import pymysql , config , uuid import config , uuid
def dbIsOK(): def getconn():
#打开数据库连接
try: try:
db = pymysql.connect(host=config.readConf()["db"]["host"], if config.readConf()["db"]["type"] == "sqlite3":
import sqlite3
conn = sqlite3.connect("APPData.db")
elif config.readConf()["db"]["type"] == "mysql":
import pymysql
conn = pymysql.connect(host=config.readConf()["db"]["host"],
port=config.readConf()["db"]["port"], port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"], user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"], password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"]) database=config.readConf()["db"]["database"])
return conn
except:
print("DB ERROR")
return 0
def dbIsOK():
#打开数据库连接
if "init" not in config.readConf():
config.updateConf({"init" : True})
init()
try:
getconn()
return True return True
except: except:
return False return False
def init():
#打开数据库连接
db = getconn()
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
#建表
cursor.execute(
'''
CREATE TABLE usersurplus (
userkey TEXT,
surplus INT);
''')
# 提交事务
db.commit()
# 关闭连接
db.close()
def userSurplus(userkey): #查询userkey剩余配额 def userSurplus(userkey): #查询userkey剩余配额
#打开数据库连接 #打开数据库连接
db = pymysql.connect(host=config.readConf()["db"]["host"], db = getconn()
port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"])
# 使用 cursor() 方法创建一个游标对象 cursor # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = %s;",[userkey]) if config.readConf()["db"]["type"] == "sqlite3":
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey])
else:
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = %s;",[userkey])
# 使用 fetchone() 方法获取单条数据. # 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone() data = cursor.fetchone()
@ -36,16 +69,15 @@ def userSurplus(userkey): #查询userkey剩余配额
def reduce_value(userkey, value): # 减去对应的值 def reduce_value(userkey, value): # 减去对应的值
#打开数据库连接 #打开数据库连接
db = pymysql.connect(host=config.readConf()["db"]["host"], db = getconn()
port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"])
# 使用 cursor() 方法创建一个游标对象 cursor # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() cursor = db.cursor()
# 执行 SQL 查询以获取当前值 # 执行 SQL 查询以获取当前值
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = %s;",[userkey]) if config.readConf()["db"]["type"] == "sqlite3":
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = ?;",[userkey])
else:
cursor.execute(f"SELECT surplus FROM usersurplus WHERE userkey = %s;",[userkey])
current_value = cursor.fetchone()[0] current_value = cursor.fetchone()[0]
# 如果没有找到用户,则返回错误信息 # 如果没有找到用户,则返回错误信息
@ -57,7 +89,10 @@ def reduce_value(userkey, value): # 减去对应的值
new_value = current_value - value new_value = current_value - value
# 更新数据库中的值 # 更新数据库中的值
cursor.execute(f"UPDATE usersurplus SET surplus= %s WHERE userkey= %s;",[new_value,userkey]) if config.readConf()["db"]["type"] == "sqlite3":
cursor.execute(f"UPDATE usersurplus SET surplus= ? WHERE userkey= ?;",[new_value,userkey])
else:
cursor.execute(f"UPDATE usersurplus SET surplus= %s WHERE userkey= %s;",[new_value,userkey])
# 提交事务 # 提交事务
db.commit() db.commit()
@ -70,11 +105,7 @@ def reduce_value(userkey, value): # 减去对应的值
def getAllKey(): def getAllKey():
#打开数据库连接 #打开数据库连接
db = pymysql.connect(host=config.readConf()["db"]["host"], db = getconn()
port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"])
# 使用 cursor() 方法创建一个游标对象 cursor # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() cursor = db.cursor()
@ -91,16 +122,15 @@ def getAllKey():
def delKey(userkey): def delKey(userkey):
#打开数据库连接 #打开数据库连接
db = pymysql.connect(host=config.readConf()["db"]["host"], db = getconn()
port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"])
# 使用 cursor() 方法创建一个游标对象 cursor # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
cursor.execute(f"DELETE FROM usersurplus WHERE userkey = %s;", [userkey]) if config.readConf()["db"]["type"] == "sqlite3":
cursor.execute(f"DELETE FROM usersurplus WHERE userkey = ?;", [userkey])
else:
cursor.execute(f"DELETE FROM usersurplus WHERE userkey = %s;", [userkey])
# 提交事务 # 提交事务
db.commit() db.commit()
@ -114,24 +144,31 @@ def delKey(userkey):
def createKey(quota,number=1,key="null"): def createKey(quota,number=1,key="null"):
#打开数据库连接 #打开数据库连接
db = pymysql.connect(host=config.readConf()["db"]["host"], db = getconn()
port=config.readConf()["db"]["port"],
user=config.readConf()["db"]["user"],
password=config.readConf()["db"]["passwd"],
database=config.readConf()["db"]["database"])
# 使用 cursor() 方法创建一个游标对象 cursor # 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor() cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 # 使用 execute() 方法执行 SQL 查询
output = [] output = []
if key == "null": if config.readConf()["db"]["type"] == "sqlite3":
for i in range(int(number)): if key == "null":
key = str(uuid.uuid1()) for i in range(int(number)):
key = str(uuid.uuid1())
output.append(key)
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota])
else:
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (?, ?);", [key, quota])
output.append(key) output.append(key)
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (%s, %s);", [key, quota])
else: else:
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (%s, %s);", [key, quota]) if key == "null":
output.append(key) for i in range(int(number)):
key = str(uuid.uuid1())
output.append(key)
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (%s, %s);", [key, quota])
else:
cursor.execute(f"INSERT INTO usersurplus (userkey,surplus) VALUES (%s, %s);", [key, quota])
output.append(key)
# 提交事务 # 提交事务
db.commit() db.commit()