如何解决pymysql连接MySQL时的1045权限拒绝错误?
解决MySQL 8.0.29下Python导入数据的1045权限错误
一、先解决root用户的权限与密码问题
本地登录MySQL
打开终端/命令行,执行:mysql -u root -p输入当前root密码登录(若忘记密码,需跳过权限验证重置,此处假设可正常登录)。
确认root用户的主机绑定
执行查询:SELECT user, host FROM mysql.user;你会看到
root对应的host是localhost(而非%),这正是之前执行SHOW GRANTS FOR root报错的原因——必须指定主机,正确命令为:SHOW GRANTS FOR 'root'@'localhost';重置/确认root密码
若不确定密码正确性,执行重置:ALTER USER 'root'@'localhost' IDENTIFIED BY '你的真实密码'; FLUSH PRIVILEGES;替换
你的真实密码为实际密码,确保Python代码中PASSWORD参数与之一致。
二、修正Python连接参数
MySQL 8.0默认使用caching_sha2_password认证插件,部分pymysql版本兼容性不足,需在连接时指定认证插件。修改连接代码:
connection = pymysql.connect(host=HOST, user=USER, password="你的真实密码", # 替换为正确密码 db=DB, port=PORT, autocommit=True, auth_plugin='mysql_native_password') # 新增该行
三、修复INSERT语句的语法错误
你的INSERT语句缺少列名的括号,会导致后续执行失败,修正为:
query = """INSERT INTO ic4projournal (transid, branchid, branchcode, currentdate, postingdatestamp, psdate, postingdate, posteddate, postedtime, intpostingdates, postingtime, postingdates, accountno, accountid, accountdesc, amount, currcode, transitcode, transcode, transtype, transtypeid, translocation, prodcode, narrative, branchadded, depositorname, addedby, addedapprovedby, workstationipadded, transmode, transtime) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
四、处理Excel数据类型匹配问题
xlrd读取日期会返回浮点数,需转换为MySQL支持的日期格式,修改循环中的值处理逻辑:
import xlrd from datetime import datetime for row in range(1, sh.nrows): values = [] for col in range(sh.ncols): cell_value = sh.cell_value(row, col) # 处理日期类型 if sh.cell_type(row, col) == xlrd.XL_CELL_DATE: cell_value = datetime(*xlrd.xldate_as_tuple(cell_value, book.datemode)).strftime('%Y-%m-%d %H:%M:%S') values.append(cell_value) cursor.execute(query, values) # 直接传列表即可,无需*values
五、验证权限
确保root@localhost拥有ic4projournal数据库的写入权限,执行:
GRANT ALL PRIVILEGES ON ic4projournal.* TO 'root'@'localhost'; FLUSH PRIVILEGES;
内容的提问来源于stack exchange,提问作者densteam-io
相关产品推荐
相关产品推荐

