imetting_backend/app/core/database.py

36 lines
1.0 KiB
Python

from fastapi import HTTPException
import mysql.connector
from mysql.connector import Error
from contextlib import contextmanager
DB_CONFIG = {
'host': 'localhost',
'database': 'imeeting',
'user': 'root',
'password': 'sagacity',
'port': 3306,
'charset': 'utf8mb4',
'autocommit': False, # 禁用自动提交
'consume_results': True # 自动消费未读结果
}
@contextmanager
def get_db_connection():
connection = None
try:
connection = mysql.connector.connect(**DB_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}")