41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
import mysql.connector
|
|
from mysql.connector import Error
|
|
|
|
def test_mysql_connection():
|
|
# MySQL 配置
|
|
config = {
|
|
'host': '192.168.2.20',
|
|
'port': 8006,
|
|
'user': 'mticloud',
|
|
'password': 'fT3KsNDahADGcWCZ',
|
|
'database': 'mti-cloud',
|
|
'charset': 'utf8mb4'
|
|
}
|
|
|
|
try:
|
|
# 建立连接
|
|
connection = mysql.connector.connect(**config)
|
|
|
|
if connection.is_connected():
|
|
print("成功连接到 MySQL 数据库!")
|
|
# 打印数据库信息
|
|
db_info = connection.get_server_info()
|
|
print(f"MySQL 服务器版本: {db_info}")
|
|
cursor = connection.cursor()
|
|
cursor.execute("SELECT DATABASE();")
|
|
record = cursor.fetchone()
|
|
print(f"当前使用的数据库: {record[0]}")
|
|
|
|
except Error as e:
|
|
print(f"连接 MySQL 时发生错误: {e}")
|
|
|
|
finally:
|
|
# 关闭连接
|
|
if connection.is_connected():
|
|
cursor.close()
|
|
connection.close()
|
|
print("MySQL 连接已关闭。")
|
|
|
|
# 执行测试
|
|
if __name__ == "__main__":
|
|
test_mysql_connection() |