初次提交
This commit is contained in:
57
backend/test_db_connection.py
Normal file
57
backend/test_db_connection.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import pymysql
|
||||
from app.core.config import settings
|
||||
|
||||
def test_mysql_connection():
|
||||
try:
|
||||
print(f"正在连接数据库: {settings.DATABASE_URL}")
|
||||
|
||||
# 解析连接字符串
|
||||
import re
|
||||
pattern = r'mysql\+pymysql://([^:]+):([^@]+)@([^:]+):(\d+)/(.+)'
|
||||
match = re.match(pattern, settings.DATABASE_URL)
|
||||
|
||||
if match:
|
||||
username, password, host, port, database = match.groups()
|
||||
print(f"主机: {host}")
|
||||
print(f"端口: {port}")
|
||||
print(f"用户: {username}")
|
||||
print(f"数据库: {database}")
|
||||
|
||||
# 尝试连接
|
||||
connection = pymysql.connect(
|
||||
host=host,
|
||||
port=int(port),
|
||||
user=username,
|
||||
password=password,
|
||||
database=database,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
|
||||
print("MySQL数据库连接成功!")
|
||||
|
||||
# 测试查询
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT VERSION()")
|
||||
version = cursor.fetchone()
|
||||
print(f"MySQL版本: {version[0]}")
|
||||
|
||||
cursor.execute("SHOW TABLES")
|
||||
tables = cursor.fetchall()
|
||||
print(f"现有表数量: {len(tables)}")
|
||||
for table in tables:
|
||||
print(f"- {table[0]}")
|
||||
|
||||
connection.close()
|
||||
return True
|
||||
|
||||
else:
|
||||
print("连接字符串格式错误")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"数据库连接失败: {str(e)}")
|
||||
print(f"错误类型: {type(e).__name__}")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_mysql_connection()
|
||||
Reference in New Issue
Block a user