28 lines
689 B
Python
28 lines
689 B
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'
|
|
}
|
|
|
|
@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():
|
|
connection.close()
|