【发布时间】: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 ...呢?