用Python MySQL Connector远程管理VPS云服务器数据库
文章分类:技术文档 /
创建时间:2026-01-28
用Python MySQL Connector远程管理VPS云服务器数据库
一、前置准备工作
1.1 配置VPS云服务器上的MySQL远程访问
首先登录你的VPS云服务器(虚拟专用服务器,通过虚拟化技术分割物理服务器得到的独立云端计算资源),完成以下4步配置:
1. 找到MySQL配置文件(通常为/etc/mysql/my.cnf或/etc/mysql/mysql.conf.d/mysqld.cnf),将`bind-address`项改为`0.0.0.0`,允许MySQL监听所有网络接口。
2. 执行命令重启MySQL服务:
sudo systemctl restart mysql3. 登录MySQL控制台,执行远程用户授权命令(替换为你的自定义信息):
GRANT ALL PRIVILEGES ON your_database.* TO 'remote_user'@'%' IDENTIFIED BY 'your_strong_password';
FLUSH PRIVILEGES;4. 开放VPS防火墙3306端口(以UFW防火墙为例):
sudo ufw allow 3306/tcp
sudo ufw reload1.2 本地Python环境准备
确保本地已安装Python 3.6及以上版本,通过pip安装Python MySQL Connector(Python官方MySQL数据库驱动):
pip install mysql-connector-python若需指定稳定版本,可执行:
pip install mysql-connector-python==8.0.33二、基础连接测试API实现
编写第一个Python脚本,测试与vps云服务器上MySQL的连接:
import mysql.connector
from mysql.connector import Error
def test_vps_mysql_connection():
connection = None
try:
# 替换为你的VPS公网IP、远程用户信息
connection = mysql.connector.connect(
host="你的VPS公网IP地址",
user="remote_user",
password="your_strong_password",
database="your_database"
)
if connection.is_connected():
db_info = connection.get_server_info()
print(f"成功连接VPS云服务器MySQL,版本:{db_info}")
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print(f"当前连接的数据库:{record[0]}")
except Error as e:
print(f"连接失败,错误信息:{e}")
finally:
if connection is not None and connection.is_connected():
cursor.close()
connection.close()
print("数据库连接已关闭")
if __name__ == "__main__":
test_vps_mysql_connection()运行脚本,若输出连接成功信息,说明基础配置已完成。此时你已打通本地与vps云服务器的MySQL数据通道,可开展后续管理操作。
三、核心远程管理API操作示例
3.1 数据查询操作
实现远程查询vps云服务器数据库中数据的API,支持字典格式返回结果:
def query_vps_mysql_data():
connection = None
try:
connection = mysql.connector.connect(
host="你的VPS公网IP地址",
user="remote_user",
password="your_strong_password",
database="your_database"
)
if connection.is_connected():
cursor = connection.cursor(dictionary=True)
# 查询示例表users中的数据
cursor.execute("SELECT id, name, age FROM users")
records = cursor.fetchall()
print("查询到的用户数据:")
for row in records:
print(f"ID: {row['id']}, 姓名: {row['name']}, 年龄: {row['age']}")
except Error as e:
print(f"查询失败,错误信息:{e}")
finally:
if connection is not None and connection.is_connected():
cursor.close()
connection.close()3.2 数据插入与提交API
实现远程向vps云服务器数据库插入数据的操作,采用参数化查询防止SQL注入:
def insert_vps_mysql_data(name, age):
connection = None
try:
connection = mysql.connector.connect(
host="你的VPS公网IP地址",
user="remote_user",
password="your_strong_password",
database="your_database"
)
if connection.is_connected():
cursor = connection.cursor()
insert_query = "INSERT INTO users (name, age) VALUES (%s, %s)"
record = (name, age)
cursor.execute(insert_query, record)
connection.commit()
print(f"成功插入{cursor.rowcount}条数据到VPS数据库")
except Error as e:
print(f"插入失败,错误信息:{e}")
# 插入失败时回滚事务
if connection is not None:
connection.rollback()
finally:
if connection is not None and connection.is_connected():
cursor.close()
connection.close()
# 调用示例
insert_vps_mysql_data("李四", 28)3.3 数据更新与删除API
实现远程更新和删除vps云服务器数据库数据的操作,注意事务提交:
def update_vps_mysql_data(user_id, new_age):
connection = None
try:
connection = mysql.connector.connect(
host="你的VPS公网IP地址",
user="remote_user",
password="your_strong_password",
database="your_database"
)
if connection.is_connected():
cursor = connection.cursor()
update_query = "UPDATE users SET age = %s WHERE id = %s"
record = (new_age, user_id)
cursor.execute(update_query, record)
connection.commit()
print(f"成功更新{cursor.rowcount}条数据")
except Error as e:
print(f"更新失败,错误信息:{e}")
connection.rollback()
finally:
if connection is not None and connection.is_connected():
cursor.close()
connection.close()
def delete_vps_mysql_data(user_id):
connection = None
try:
connection = mysql.connector.connect(
host="你的VPS公网IP地址",
user="remote_user",
password="your_strong_password",
database="your_database"
)
if connection.is_connected():
cursor = connection.cursor()
delete_query = "DELETE FROM users WHERE id = %s"
record = (user_id,)
cursor.execute(delete_query, record)
connection.commit()
print(f"成功删除{cursor.rowcount}条数据")
except Error as e:
print(f"删除失败,错误信息:{e}")
connection.rollback()
finally:
if connection is not None and connection.is_connected():
cursor.close()
connection.close()四、安全与故障排查注意事项
4.1 安全优化建议
1. 避免用`%`授权所有IP,可指定本地固定IP段,如`GRANT ... TO 'remote_user'@'192.168.1.%'`,缩小访问范围降低风险。
2. 启用SSL加密连接,在connect方法中添加`ssl_disabled=False`参数,提升vps云服务器与本地数据传输的安全性。
3. 不要硬编码密码,用环境变量或加密配置文件存储敏感信息,防止数据泄露。
4. 定期更新MySQL和Python库版本,回收不必要的数据库权限,筑牢安全防线。
4.2 常见故障排查
1. 连接超时:检查VPS防火墙3306端口是否开放,MySQL服务是否正常运行,本地网络能否访问VPS公网IP。
2. 权限拒绝:确认MySQL授权语句正确,已执行`FLUSH PRIVILEGES`刷新权限,用户名与密码无误。
3. 数据不生效:检查是否调用`connection.commit()`提交事务,未提交的操作不会写入vps云服务器的数据库。
工信部备案:苏ICP备2025168537号-1