MySQL错误:Access denied for user 'name'@'localhost' (using password: YES) 解决方法

问题描述

在使用Java连接MySQL数据库时,经常会遇到 Access denied for user 'name'@'localhost' (using password: YES) 的错误信息。这意味着你尝试使用的用户名 ('name') 在连接到 'localhost' 上的MySQL服务器时被拒绝访问,即使你提供的密码是正确的。

可能的原因及解决方法

  1. 用户名或密码错误: 仔细检查 DatabaseConnector 类中提供的用户名 (USERNAME) 和密码 (PASSWORD) 是否与你实际的MySQL凭据匹配。

    
        public static Connection getConnection() throws SQLException {           return DriverManager.getConnection(URL, USERNAME, PASSWORD);       }   }   ```
    
    
  2. 用户权限不足: 确保你尝试连接的用户名具有访问目标数据库 (exam_system) 的权限。你可以使用 phpMyAdmin 或 MySQL Workbench 等工具来管理用户权限。

  3. 数据库服务未启动: 确认你的MySQL服务器正在运行。如果没有,你需要启动它才能连接。

  4. 防火墙阻止: 检查你的防火墙设置,确保它没有阻止来自你的应用程序的MySQL连接 (端口 3306)。

代码优化建议

除了解决连接问题外,还可以对代码进行一些优化:

  • 使用PreparedStatement防止SQL注入: 将用户输入直接拼接到SQL语句中存在安全风险。使用 PreparedStatement 可以有效防止SQL注入攻击。

  • 资源关闭: 确保在使用完数据库连接、语句和结果集后及时关闭它们,以释放资源。

示例

以下是使用 PreparedStatement 和资源关闭的优化代码示例:javapublic static void studentLogin() { Scanner scanner = new Scanner(System.in); System.out.println('请输入学号:'); int studentId = scanner.nextInt(); System.out.println('请输入密码:'); String password = scanner.next();

Connection conn = null;    PreparedStatement statement = null;    ResultSet result = null;

try {        conn = DatabaseConnector.getConnection();        String sql = 'SELECT * FROM students WHERE student_id = ? AND password = ?';        statement = conn.prepareStatement(sql);        statement.setInt(1, studentId);        statement.setString(2, password);        result = statement.executeQuery();

    if (result.next()) {            // 登录成功后的逻辑        } else {            System.out.println('学号或密码错误,请重新登录!');        }    } catch (SQLException e) {        e.printStackTrace();        System.out.println('登录失败,请重新尝试!');    } finally {        // 关闭资源        try { if (result != null) result.close(); } catch (SQLException e) { e.printStackTrace(); }        try { if (statement != null) statement.close(); } catch (SQLException e) { e.printStackTrace(); }        try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }    }}

总结

Access denied for user 'name'@'localhost' (using password: YES) 错误通常是由于数据库连接配置错误、用户权限问题或数据库服务未启动造成的。仔细检查这些方面,并根据需要修改代码,就可以解决这个问题。

MySQL错误:Access denied for user 'name'@'localhost' (using password: YES) 解决方法

原文地址: https://www.cveoy.top/t/topic/fZ3y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录