java - 该方法没有正确检查值
问题描述
static boolean checkCode(String Code, Connection conn) throws SQLException {
Statement s;
String cc = null;
try {
String Statement = "SELECT Code from Courses where Code="+ Code;
s = conn.createStatement();
ResultSet rs = s.executeQuery(Statement);
while (rs.next()) {
cc = rs.getString("Code");
}
if((Code.equalsIgnoreCase(cc)))
return true;
else
return false;
}
catch (SQLException e) {}
return false;
}
我正在使用 switch 案例,3 个案例无法正常工作(使用课程代码删除,使用课程代码更新,并使用课程代码查看特定课程)所以我认为 checkCode 方法中的错误。有人可以帮忙吗?
解决方案
您正在选择一个值等于自身的值。我只会得到匹配记录的计数。接下来,您不会关闭您在方法中打开的任何资源。而且,您正在默默地吞下发生的任何异常。最后,您没有使用PreparedStatement
,因此您的查询(至少乍一看)容易受到 sql 注入的攻击。
就像是,
static boolean checkCode(String Code, Connection conn) throws SQLException {
String query = "SELECT count(*) from Courses where Code=?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, Code);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
推荐阅读
- android - 将数据存储在通过改造接收的对象中
- python - 如何将参数发送到名为间隔的函数
- java - 为什么 bufferedreader 对这些值返回 null?
- javascript - 了解 Axios 创建的功能
- c++ - 犰狳 - 长向量中每个小块的范数
- java - 返回数组列表的算法的空间复杂度是多少?
- customization - 你有什么建议开始这样的项目?启动 teespring vistaprint
- google-sheets - 我可以在 Google 表格上的 Sparkline 中添加 0-100% 的数字吗?
- ios - iOS 检测活人脸(不是照片)
- django - 使用条带令牌对带有条带元素的信用卡进行收费