使用XAMPP搭建登录页数据库连接时遇MySQL 1045权限错误求助
解决XAMPP MySQL连接权限错误(1045 Access Denied)
错误原文:mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
中文翻译:mysql.connector.errors.ProgrammingError: 1045 (28000): 用户 'root'@'localhost' 拒绝访问(未使用密码)
解决步骤:
确认并修正MySQL root密码
打开XAMPP控制面板,启动MySQL后点击「Admin」进入phpMyAdmin,切换到「用户账户」页面,找到root@localhost条目:- 若该用户已设置密码,将
main.py中password=""替换为对应的密码; - 若确实未设置密码,继续下一步检查权限配置。
- 若该用户已设置密码,将
检查root用户的localhost访问权限
在phpMyAdmin的用户账户页,编辑root@localhost的权限:- 确保勾选
SELECT权限(你的代码需要执行查询操作),测试阶段可直接勾选「全部权限」; - 保存权限设置后重启MySQL服务。
- 确保勾选
修复SQL语句的语法错误与注入漏洞
原代码的SQL存在两处致命问题:- 拼写错误:
select *form user应为select * from user; - 字符串拼接导致SQL注入,且引号位置错误。
替换为安全的参数化查询:
# 替换原execute行 mycursor.execute("SELECT * FROM user WHERE name = %s AND password = %s", (username, password))- 拼写错误:
优化数据库连接管理
原代码中mydb.commit()属于冗余代码(查询操作无需提交事务),且未正确管理连接资源。建议用with语句自动处理连接和游标:@app.route('/result',methods=['POST','GET']) def result(): if request.method=='POST': signup=request.form username=signup['user'] password=signup['pass'] with mysql.connector.connect( host="localhost", user="root", password="你的密码", database="user-system" ) as mydb: with mydb.cursor() as mycursor: mycursor.execute("SELECT * FROM user WHERE name = %s AND password = %s", (username, password)) count=mycursor.rowcount if count==1: return render_template("test.html") elif count> 1: return "多个用户匹配" else: return render_template("login.html") return render_template("login.html")
内容的提问来源于stack exchange,提问作者ANAND KHAROTE
相关产品推荐
相关产品推荐

