import mysql.connector
from mysql.connector import Error
def test_database_connection():
try:
# 连接到远程 MySQL 数据库
connection = mysql.connector.connect(
host='192.168.xxx.xxx',
port=3306, #数据库一般都是3306
user='xxx', # 替换为你的数据库用户名
password='xxxxxx', # 替换为你的数据库密码
database='xxxxxx' # 替换为你要连接的数据库名
)
if connection.is_connected():
print("成功连接到数据库")
# 创建一个游标对象
cursor = connection.cursor()
# 查询数据
cursor.execute('SELECT * FROM profile')
results = cursor.fetchall()
# 打印查询结果
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
connection.close()
print("数据库操作成功!")
else:
print("数据库连接失败")
except Error as e:
print(f"数据库连接测试失败:{e}")
# 运行测试函数
test_database_connection()
注:在此之前需要被连接的机子给你的电脑ip开权限。ta如何给你权限,参考下一篇文章