首先要在MySQL数据库中,为要远程访问的主机创建用户账号并授予权限:
假设远程用户IP地址为192.168.190.152,要访问的数据库为school,school数据库已经创建,为此用户创建账户名为z305,密码为123456.
create user 'z305'@'192.168.190.152' identified by '123456';#创建用户
grant ALL ON school.* to'z305'@'192.168.190.152'; #将对数据库school的所有权限授予z305
FLUSH PRIVILEGES; #重新加载权限,
show grants for 'z305'@'192.168.190.152';#查看权限
然后就可以在IP地址为192.168.190.152的电脑上使用z305的账号访问MySQL数据库了。
# mysql1.py
import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='192.168.*.*',#school数据库所在主机IP
port=3306,
user='z305', # 授予权限账号
passwd='123456', # 密码
db='school',
charset='utf8'
)
# 获取游标
cursor = connect.cursor()
# 执行SQL查询
cursor.execute("SELECT VERSION()")
# 获取单条数据
version = cursor.fetchone()
# 打印输出
print("MySQL数据库版本是:%s" % version)
# 关闭数据库连接
connect.close()