【问题标题】:Username and password exist but not found and authenticated用户名和密码存在但未找到和验证
【发布时间】:2015-06-15 21:50:42
【问题描述】:

从数据库中检索密码和用户名。如果返回一行,则表示存在用户。但是,下面的代码表示即使用户名和密码正确,用户也不存在。

if(con != null) {
    try {
        String query = "select * from users where username = '"+user.getText()+"' and password = '"+pasword.getText()+"'";
        PreparedStatement ps = con.prepareStatement(query);

        ResultSet rs = ps.executeQuery();
        int count = 0;

        while(rs.next()) {
            count = count + 1;
        }

        if(count == 1) {
            JOptionPane.showMessageDialog(null, "user exist");
        } else {
            JOptionPane.showMessageDialog(null, "user doesnot exist");
        }

        rs.close();
        ps.close();
    } catch (Exception e1) {
    }
}

【问题讨论】:

  • 你检查过 user.getText() 和 password.getText() 值吗? r 它们是否真的存在于数据库中?
  • } catch (Exception e1){ } 不要忽略错误输出!将其更改为(至少)} catch (Exception e1){ e1.printStackTrace(); }
  • 该代码已经成熟,可以进行 sql 注入了。
  • 使用PreparedStatement 没有意义,因为您没有利用 API 提供的功能。请参阅Using Prepared Statements 了解如何使用它。如果您要计算匹配项,那么为什么不直接使用 select count(*) from ... 呢?

标签: java mysql swing


【解决方案1】:

这是一个合理的代码,但你应该编写

e.printStackTrace() 

在 catch 块中,可能会发生异常。检查user.getText()password.getText() 内容,也可以应用user.getText().trim() 例如删除de 空格。然后试试这个:

while(rs.next()) {
        count++;
}

if(count > 0) {
    JOptionPane.showMessageDialog(null, "user exist");
} else {
    JOptionPane.showMessageDialog(null, "user doesnot exist");
}

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2013-12-26
    • 2016-01-24
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多