pymysql模块操作数据库及连接报错解决方法
import pymysql
sql = "select host,user,password from user" #想要执行的MySQL语句
#sql = 'create database sss character set utf8'
#打开数据库连接
db = pymysql.connect(host="192.168.254.40", user="root",
password="root", db="mysql", port=3306)
cur = db.cursor()#使用cursor()方法获取操作游标
cur.execute(sql) # 执行sql语句
results = cur.fetchall() # 获取查询的所有记录
for i in results:#遍历结果
print(i)
db.close() # 关闭连接
pymysql:Mysql拒绝从远程访问的解决办法
报错内容
Traceback (most recent call last):
File "E:/untitled1/lvs_rr.py", line 15, in <module>
password="1", db="mysql", port=3306)
File "E:\untitled1\lib\site-packages\pymysql\__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 325, in __init__
return Connection(*args, **kwargs)
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 325, in __init__
self.connect()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 599, in connect
self._request_authentication()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 861, in _request_authentication
auth_packet = self._read_packet()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 684, in _read_packet
packet.check_error()
File "E:\untitled1\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "E:\untitled1\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 325, in __init__
self.connect()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 599, in connect
self._request_authentication()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 861, in _request_authentication
auth_packet = self._read_packet()
File "E:\untitled1\lib\site-packages\pymysql\connections.py", line 684, in _read_packet
packet.check_error()
File "E:\untitled1\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "E:\untitled1\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
解决方法:
添加用户允许从任何主机连接到mysql服务器
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
即时生效
FLUSH PRIVILEGES;