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:\Pycham\venv\lib\site-packages\pymysql\__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "C:\Pycham\venv\lib\site-packages\pymysql\connections.py", line 325, in __init__
self.connect()
File "C:\Pycham\venv\lib\site-packages\pymysql\connections.py", line 598, in connect
self._get_server_information()
File "C:\Pycham\venv\lib\site-packages\pymysql\connections.py", line 975, in _get_server_information
packet = self._read_packet()
File "C:\Pycham\venv\lib\site-packages\pymysql\connections.py", line 684, in _read_packet
packet.check_error()
File "C:\Pycham\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "C:\Pycham\venv\lib\site-packages\pymysql\err.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()

