首页 > 解决方案 > 该方法没有正确检查值

问题描述

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 方法中的错误。有人可以帮忙吗?

标签: javasqlmethodsoracle11g

解决方案


您正在选择一个值等于自身的值。我只会得到匹配记录的计数。接下来,您不会关闭您在方法中打开的任何资源。而且,您正在默默地吞下发生的任何异常。最后,您没有使用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;
}

推荐阅读