PyCharm使用Anaconda创建环境连接MySQL

    科技2025-04-25  13

    后期可能要从opc数据库搞点东西,所以先学一下MySQL

    至于为什么要这么花里胡哨是因为手头正好有这些工具,懒得去搞其它的..

    本文所用配置为:win7,python2.7,MySQL8.0.12,pycharm2020.2

    环境配置参考https://blog.csdn.net/jiahanghacker/article/details/89195088  

    我就不复制粘贴了

    但是这个代码是执行不了的

    错误:1251:client does not support authentication protocol requested by server...

    原因:mysql8 之前的版本中加密规则是mysql_native_password,而在mysql8之后,加密规则是caching_sha2_password

    很明显使用

    MySQLdb.connect

    的加密规则是mysql_native_password,而MySQL加密规则为caching_sha2_password,所以产生错误

    所以我们要把MySQL用户密码登录的加密规则还原成mysql_native_password这种加密方式

    解决方法:

    1.通过mysql -u root -p 进入mysql的命令行模式

    2.然后use mysql;

    3.查询表中的相关信息 select user,host from user;

    这里就是访问失败的原因

    我是用Anaconda的环境访问的,图中w2020105是我的Anacaonda创建的环境的名字,所以改的就是这个的加密方式

    4.修改,将下边的w2020105改为自己的环境名字,其中有些人的host不是%,可能是localhost,需要将下边的%改为localhost,从上图中可以看到host的属性

    alter user w2020105'@'%' identified by '现在的密码' password expire never;

    alter user 'w2020105'@'%' identified with mysql_native_password by '新的密码';

    flush privileges;刷新一下权限配置

    5.查看修改结果

    select user,host,plugin from user where user='w2020105';

    可以看到现在已经改为mysql_native_password

    6.验证,pycharm执行代码

    #!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打开数据库连接 db = MySQLdb.connect("localhost", "w2020105", "123456", "mysql") # 使用cursor()方法获取操作游标 cursor = db.cursor() # 使用execute方法执行SQL语句 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取一条数据 data = cursor.fetchone() print ("Database version : %s " % data) # 关闭数据库连接 db.close()

    执行结果

    Database version : 8.0.12

    图片死活传不上去了..

    另附:

    ERROR 1396:https://blog.csdn.net/q258523454/article/details/84555847

    (参考)ERROR 1251:https://blog.csdn.net/yubin1285570923/article/details/83352491

    MySQL8.0环境变量配置(最下边一步到位):https://blog.csdn.net/weixin_41955953/article/details/81272849

    因修改ini文件导致MySQL服务启动后停止的解决方法:https://www.cnblogs.com/pandaly/p/11738789.html

    Processed: 0.009, SQL: 8