126 lines
3.4 KiB
Python
126 lines
3.4 KiB
Python
import json
|
|
import os
|
|
|
|
import pymysql
|
|
|
|
|
|
class Mysql:
|
|
def __init__(self):
|
|
self.req_hds = []
|
|
self.req_hds2 = []
|
|
self.host = 'localhost'
|
|
self.port = 3306
|
|
self.db = 'mjz'
|
|
self.hd_ok = 1
|
|
self.conn = self.init_mysql()
|
|
|
|
def init_mysql(self):
|
|
conn = pymysql.connect(
|
|
host=self.host,
|
|
port=self.port,
|
|
user='root',
|
|
password='ader146090',
|
|
db=self.db,
|
|
charset='utf8mb4',
|
|
autocommit=True, # 自动提交,避免长时间占用连接
|
|
connect_timeout=10, # 连接超时
|
|
read_timeout=30, # 读取超时
|
|
write_timeout=30, # 写入超时
|
|
max_allowed_packet=16*1024*1024 # 最大数据包大小
|
|
)
|
|
if conn:
|
|
print('数据库连接成功')
|
|
return conn
|
|
|
|
def check_connection(self):
|
|
"""检查数据库连接是否有效,无效则重新连接"""
|
|
if not self.conn:
|
|
self.conn = self.init_mysql()
|
|
return
|
|
|
|
# 检查连接是否还活着
|
|
self.conn.ping(reconnect=True)
|
|
|
|
def update(self,sql,values):
|
|
self.check_connection()
|
|
aa = self.conn.cursor()
|
|
aa.execute(sql,values)
|
|
aa.close()
|
|
|
|
def insert(self,sql,values):
|
|
self.check_connection()
|
|
aa = self.conn.cursor()
|
|
aa.execute(sql,values)
|
|
aa.close()
|
|
|
|
def insert_many(self,sql,values):
|
|
self.check_connection()
|
|
aa = self.conn.cursor()
|
|
result = aa.executemany(sql,values)
|
|
aa.close()
|
|
return result
|
|
|
|
def get(self,sql):
|
|
self.check_connection()
|
|
aa = self.conn.cursor()
|
|
aa.execute(sql)
|
|
result = aa.fetchall()
|
|
aa.close()
|
|
return result
|
|
|
|
def insert_headers(self,path, ty):
|
|
n = []
|
|
for root,dirs,files in os.walk(path):
|
|
if len(files)>0:
|
|
for file in files:
|
|
if file in ["render","products","food"]:
|
|
path2 = os.path.join(root,file)
|
|
with open(path2, 'r', encoding='utf-8') as f:
|
|
headersdata = json.load(f)
|
|
n.append([json.dumps(headersdata), ty, file])
|
|
sql = """INSERT IGNORE INTO headers
|
|
(header_content, type1, type2)
|
|
VALUES (%s, %s, %s)
|
|
"""
|
|
result = self.insert_many(sql,n)
|
|
print(result,'个包插入成功')
|
|
|
|
def update_headers(self,id,unavailable_poi_ids,count):
|
|
sql = '''
|
|
UPDATE headers set `unavailable_poi_ids`=%s,`count`=%s WHERE id=%s
|
|
'''
|
|
result = self.update(sql,(unavailable_poi_ids,count,id))
|
|
print('更新成功')
|
|
|
|
def close(self):
|
|
"""安全关闭数据库连接"""
|
|
if self.conn:
|
|
self.conn.close()
|
|
self.conn = None
|
|
print('数据库连接已关闭')
|
|
|
|
def __del__(self):
|
|
"""析构函数,确保连接被正确关闭"""
|
|
self.close()
|
|
|
|
|
|
def get_headers(my):
|
|
sql = '''
|
|
select * from headers where is_ok = 1
|
|
'''
|
|
result = my.get(sql)
|
|
return result
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
my = Mysql()
|
|
result = get_headers(my)
|
|
products = []
|
|
render = []
|
|
for i in result:
|
|
if i[4]=="products":
|
|
products.append(i)
|
|
elif i[4]=="render":
|
|
render.append(i)
|
|
print(i) |