imetting_backend/app/core/database.py

26 lines
839 B
Python

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