一、连接前的准备(如果报错可以从以下几个方面检查一下)
1.检查mysql服务
查看mysql服务是否开启
sudo systemctl status mysql
若没开启,开启mysql服务
sudo systemctl start mysql
2.检查mysql的3306端口
查看3306端口是否打开
netstat -an|grep 3306
若没打开,打开3306端口
sudo ufw allow 3306/tcp
3.修改配置文件
配置文件及其路径为
/etc/mysql/mysql.conf.d/mysqld.cnf
找到 bind-address 将默认的127.0.0.1修改值为 0.0.0.0
重启mysql
sudo service mysql restart
4.检查用户权限
查看用户是否允许任何主机远程连接
SELECT User, Host FROM mysql.user WHERE User = 'your_username';
如果Host
列包含%
,则表示该用户可以从任何主机进行连接。如果Host
列包含特定的IP地址或主机名,则用户只能从那些地址或主机进行连接。
若不允许(只能本地),开启任意主机远程连接或者开启特定主机连接
GRANT ALL PRIVILEGES ON *.* TO 'your_username'@'%' IDENTIFIED BY 'your_password' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'your_username'@'192.168.111.%' IDENTIFIED BY 'your_password' WITH GRANT OPTION;
刷新权限
FLUSH PRIVILEGES;
二、开始连接
安装mysql-connector-python包
pip install mysql-connector-python
python代码
import mysql.connector
# MySQL服务器配置
host = 'your_server_ip'
port = 3306
user = 'your_username'
password = 'your_password'
db_name = 'your_database'
# 创建连接
try:
# 使用sha256_password插件(MySQL 8.0默认)
connection = mysql.connector.connect(
host=host,
port=port,
user=user,
password=password,
database=db_name,
auth_plugin='sha256_password' # 指定身份验证插件
)
# 连接成功,可以进行后续操作
print("连接成功!")
# 创建一个游标对象
cursor = connection.cursor()
# 使用游标执行SQL查询
sql = "SELECT * FROM your_table"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
connection.close()
except mysql.connector.Error as err:
print(f"连接失败: {err}")
确保将your_server_ip、your_username、your_password/、your_database和your_table替换为你自己的MySQL服务器IP、用户名、密码、数据库名和表名
运行得到查询结果
如有错误,请大佬们多多指教(抱拳)。