【问题标题】:the method does not check the value properly该方法没有正确检查值
【发布时间】:2020-08-16 15:48:44
【问题描述】:
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 方法中的错误。有人可以帮忙吗?

【问题讨论】:

    标签: java sql methods oracle11g


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多