imetting_backend/app/core/database.py

26 lines
839 B
Python
Raw Normal View History

2025-08-05 01:46:40 +00:00
from fastapi import HTTPException
import mysql.connector
from mysql.connector import Error
2025-09-03 10:11:07 +00:00
from app.core.config import DATABASE_CONFIG
2025-08-05 01:46:40 +00:00
from contextlib import contextmanager
@contextmanager
def get_db_connection():
connection = None
try:
2025-09-03 10:11:07 +00:00
connection = mysql.connector.connect(**DATABASE_CONFIG)
2025-08-05 01:46:40 +00:00
yield connection
except Error as e:
print(f"数据库连接错误: {e}")
raise HTTPException(status_code=500, detail="数据库连接失败")
finally:
if connection and connection.is_connected():
2025-08-28 08:02:59 +00:00
try:
# 确保清理任何未读结果
if connection.unread_result:
connection.consume_results()
connection.close()
except Exception as e:
print(f"关闭数据库连接时出错: {e}")