TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
防注入的最有效,最简单的方法是 使用预编译的PreparedStatement, 而不是使用拼凑SQL的 Statement, 比如判断用户名和密码的例子,应该用:
/**
* 一段防止SQL注入的使用预编译的PreparedStatement的代码例子
*
* @param username 用户名
* @param password 密码
* @return 成功返回true,否则返回false
*/
public static boolean checkLogin(String username, String password) {
Connection con = null;// 数据库连接部分我就不写了
PreparedStatement stat = null;
ResultSet rs = null;
try {
// 预编译语句
stat = con.prepareStatement("select count(*) from t_user where username=? and password=?");
// 设置2个参数
stat.setString(1, username);
stat.setString(2, password);
// 执行
rs = stat.executeQuery();
if (rs.next()) {
return rs.getInt(1) > 0;
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
// 这里关闭资源的方法我也不写了
}
}[/code] |
|