pymysql:Mysql拒绝从远程访问的解决办法
pymysql连接数据库
# 导入pymysql模块 import pymysql # 连接database conn = pymysql.connect( host="192.168.1.1", user="root", password="password", db ="test", charset ="utf8") # 得到一个可以执行SQL语句的光标对象 cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示 # 得到一个可以执行SQL语句并且将结果作为字典返回的游标 # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 定义要执行的SQL语句 sql = "select * from account" # 执行SQL语句 cursor.execute(sql) # 关闭光标对象 cursor.close() # 关闭数据库连接 conn.close()
报错内容
Traceback (most recent call last): File "C:/Pycham/Mysql/test.py", line 10, in <module> charset ="utf8") File "C:Pychamvenvlibsite-packagespymysql\__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "C:Pychamvenvlibsite-packagespymysqlconnections.py", line 325, in __init__ self.connect() File "C:Pychamvenvlibsite-packagespymysqlconnections.py", line 598, in connect self._get_server_information() File "C:Pychamvenvlibsite-packagespymysqlconnections.py", line 975, in _get_server_information packet = self._read_packet() File "C:Pychamvenvlibsite-packagespymysqlconnections.py", line 684, in _read_packet packet.check_error() File "C:Pychamvenvlibsite-packagespymysqlprotocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "C:Pychamvenvlibsite-packagespymysqlerr.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1130, "Host '219.139.78.81' is not allowed to connect to this MariaDB server")
解决办法
Mysql必须开启远程访问权限 才允许远程连接。
root帐户是无法远程登陆的,只可以本地登陆。
1.使用mysql数据库
use mysql;
2.添加用户允许从任何主机连接到mysql服务器
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
允许任何IP地址(上面的 % 就是这个意思)的电脑使用root用户 和密码(password)来访问这个MySQL Server 。
如果你想允许用户root从ip为192.168.1.1的主机连接到mysql服务器,并使用password作为密码 GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.1' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
如果你想允许用户root从ip为192.168.1.1的主机连接到mysql服务器的dk数据库,并使用password作为密码
GRANT ALL PRIVILEGES ON dk.* TO 'root'@'192.168.1.1' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
3.及时生效
FLUSH PRIVILEGES
4.测试
# 导入pymysql模块 import pymysql # 连接database conn = pymysql.connect( host="192.168.1.1", user="root", password="password", db ="test", charset ="utf8") # 得到一个可以执行SQL语句的光标对象 cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示 # 得到一个可以执行SQL语句并且将结果作为字典返回的游标 # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 定义要执行的SQL语句 sql = "select version()" # 执行SQL语句 cursor.execute(sql) # #使用fetchone()方法获取一条数据 data = cursor.fetchone() print("Mysql version : %s"%data) # 关闭光标对象 cursor.close() # 关闭数据库连接 conn.close()