taibai_shopping/test_db_connection.py
2025-07-04 19:07:35 +08:00

121 lines
3.3 KiB
Python

import pymysql
import sys
# 数据库配置
config = {
'host': '27.124.22.104',
'user': 'taibai',
'password': 'taibaishopping',
'database': 'online_shopping',
'port': 3306,
'charset': 'utf8mb4',
'connect_timeout': 10, # 设置连接超时时间
'read_timeout': 10,
'write_timeout': 10
}
def test_connection():
try:
print("正在测试数据库连接...")
print(f"主机: {config['host']}")
print(f"端口: {config['port']}")
print(f"用户: {config['user']}")
print(f"数据库: {config['database']}")
# 尝试连接数据库
connection = pymysql.connect(**config)
print("✅ 数据库连接成功!")
# 测试查询
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)}")
if tables:
print("现有表:")
for table in tables:
print(f" - {table[0]}")
connection.close()
return True
except pymysql.Error as e:
print(f"❌ 数据库连接失败: {e}")
return False
except Exception as e:
print(f"❌ 连接过程中发生错误: {e}")
return False
if __name__ == "__main__":
if test_connection():
print("\n数据库连接测试通过,可以继续运行应用。")
else:
print("\n请检查数据库配置或网络连接。")
sys.exit(1)
import pymysql
import sys
# 数据库配置
config = {
'host': '27.124.22.104',
'user': 'taibai',
'password': 'taibaishopping',
'database': 'online_shopping',
'port': 3306,
'charset': 'utf8mb4',
'connect_timeout': 10, # 设置连接超时时间
'read_timeout': 10,
'write_timeout': 10
}
def test_connection():
try:
print("正在测试数据库连接...")
print(f"主机: {config['host']}")
print(f"端口: {config['port']}")
print(f"用户: {config['user']}")
print(f"数据库: {config['database']}")
# 尝试连接数据库
connection = pymysql.connect(**config)
print("✅ 数据库连接成功!")
# 测试查询
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)}")
if tables:
print("现有表:")
for table in tables:
print(f" - {table[0]}")
connection.close()
return True
except pymysql.Error as e:
print(f"❌ 数据库连接失败: {e}")
return False
except Exception as e:
print(f"❌ 连接过程中发生错误: {e}")
return False
if __name__ == "__main__":
if test_connection():
print("\n数据库连接测试通过,可以继续运行应用。")
else:
print("\n请检查数据库配置或网络连接。")
sys.exit(1)