问题:生成日报时MySQL连接超时 修复: - 增加 connect_timeout: 30秒 - 增加 read_timeout: 60秒 - 增加 write_timeout: 60秒 数据库连接测试成功,配置正确。 如果是沙箱环境网络限制,建议在本地运行。 Coze-Commit-Type: user Coze-User-ID: 3722323274763196 Coze-Conversation-ID: 9894087
54 lines
1.3 KiB
Python
54 lines
1.3 KiB
Python
"""
|
|
数据库连接配置
|
|
"""
|
|
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,
|
|
'autocommit': True,
|
|
'connect_timeout': 30, # 连接超时30秒
|
|
'read_timeout': 60, # 读取超时60秒
|
|
'write_timeout': 60 # 写入超时60秒
|
|
}
|
|
|
|
|
|
@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 |