Python3 PyMySQL 连接 MySQL 数据库问题,在Win10上如何解决?
python3 连接 MySQL 数据库问题, win10 在 cmd 上可以使用 root 加 pssword 连上 mysql,mysql -u root -p password; 但是使用 PyMySQL 却连接不上,报 pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")
CMD 可以连接
Microsoft Windows [版本 10.0.16299.371] (c) 2017 Microsoft Corporation。保留所有权利。
C:\Users\shuer>mysql -u root -p Enter password: *************** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 52 Server version: 8.0.11 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Python3 PyMySQL 连接 MySQL 数据库问题,在Win10上如何解决?
Use password no ?
在Win10上用PyMySQL连MySQL,常见问题就几个地方,照着排查就行。
1. 先确认基础环境 确保你装了Python3和PyMySQL:
pip install PyMySQL
2. 连接代码模板 用这个基础代码测试:
import pymysql
# 替换成你的实际信息
connection = pymysql.connect(
host='localhost', # 如果是本地就写localhost
user='你的用户名', # 默认可能是root
password='你的密码',
database='数据库名', # 你要连接的数据库
port=3306, # MySQL默认端口
charset='utf8mb4' # 字符集
)
try:
with connection.cursor() as cursor:
# 执行个简单查询
cursor.execute("SELECT VERSION()")
result = cursor.fetchone()
print(f"MySQL版本: {result[0]}")
finally:
connection.close()
3. 常见错误及解决
错误1:pymysql.err.OperationalError: (2003, "Can't connect to MySQL server")
- MySQL服务没启动:去服务里启动“MySQL”服务
- 端口不对:检查是不是3306,改过端口就改代码里的port
- 主机名写错:本地用
localhost或127.0.0.1
错误2:pymysql.err.OperationalError: (1045, "Access denied")
- 密码错了:确认MySQL密码
- 用户没权限:用这个命令给用户授权:
GRANT ALL PRIVILEGES ON *.* TO '用户名'@'localhost' IDENTIFIED BY '密码';
FLUSH PRIVILEGES;
错误3:pymysql.err.InternalError: (1049, "Unknown database")
- 数据库不存在:先创建数据库:
CREATE DATABASE 数据库名;
4. 如果还不行
- 关防火墙试试:有时候防火墙会挡本地连接
- 检查MySQL的
my.ini或my.cnf文件,确保有bind-address = 0.0.0.0(允许所有IP连接)
总结建议: 按这个流程排查,大部分连接问题都能解决。
使得,我 cmd 上可以连,python 那边也写了 password,但还是报错,using password no
你不贴代码,怎么看。。
就这里 connection = pymysql.connect(host=‘localhost’,
user=‘root’,
db=‘wocao’,
password=‘xxxxxx’)
密码是对的,但报错
ok 啦,不知道为什么用 mysql-connector-python 就 ok 啦

