2026-07-09 11:26:23 +08:00
|
|
|
"""
|
|
|
|
|
数据库连接配置
|
|
|
|
|
"""
|
|
|
|
|
import pymysql
|
|
|
|
|
from contextlib import contextmanager
|
|
|
|
|
|
|
|
|
|
# 数据库配置
|
|
|
|
|
DB_CONFIG = {
|
|
|
|
|
'host': 'haoslm2.xicp.net',
|
|
|
|
|
'port': 10216,
|
|
|
|
|
'user': 'root',
|
|
|
|
|
'password': 'DsideaL147258369',
|
|
|
|
|
'database': 'yltcharge',
|
|
|
|
|
'charset': 'utf8mb4',
|
|
|
|
|
'cursorclass': pymysql.cursors.DictCursor,
|
2026-07-10 10:01:04 +08:00
|
|
|
'autocommit': True,
|
|
|
|
|
'connect_timeout': 30, # 连接超时30秒
|
|
|
|
|
'read_timeout': 60, # 读取超时60秒
|
|
|
|
|
'write_timeout': 60 # 写入超时60秒
|
2026-07-09 11:26:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
|
def get_connection():
|
|
|
|
|
"""获取数据库连接(上下文管理器)"""
|
|
|
|
|
conn = pymysql.connect(**DB_CONFIG)
|
|
|
|
|
try:
|
|
|
|
|
yield conn
|
|
|
|
|
finally:
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def execute_query(sql, params=None):
|
|
|
|
|
"""执行查询并返回结果"""
|
|
|
|
|
with get_connection() as conn:
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
cursor.execute(sql, params)
|
|
|
|
|
return cursor.fetchall()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def execute_update(sql, params=None):
|
|
|
|
|
"""执行更新操作"""
|
|
|
|
|
with get_connection() as conn:
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
cursor.execute(sql, params)
|
|
|
|
|
return cursor.rowcount
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def execute_insert(sql, params=None):
|
|
|
|
|
"""执行插入操作并返回插入ID"""
|
|
|
|
|
with get_connection() as conn:
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
cursor.execute(sql, params)
|
|
|
|
|
return cursor.lastrowid
|