【问题标题】:Giving error that wrong return type in java在java中给出错误返回类型的错误
【发布时间】:2017-05-30 10:54:11
【问题描述】:

我正在读取MySql 中的数据库并将值存储在ArrayList 中并返回它..

public ArrayList getData(String rule) {
    try {
        String q = "select distinct email_id from logs where rule ='" + rule + "';";
        System.out.println(q);
        rs = st.executeQuery(q);
        ArrayList emails = new ArrayList();
        while (rs.next()) {
            emails.add(rs.getString("email_id"));
        }
        return emails;

    } catch (Exception e) {
        System.out.println("" + e);
    }
}

这段代码有什么问题.. 它给出了一个错误“它必须返回ArrayList 类型的结果”.. 但我只返回ArrayList 类型的'电子邮件'..帮我找出这个错误..

【问题讨论】:

  • 提示:如果出现异常怎么办?在这种情况下程序应该做什么?不是在那种情况下返回的。检查所有可能的代码执行流程。
  • 作为旁注:GENERICS,不要使用 rawtypes..
  • 你在 try 块中返回它们,当发生异常时你不会返回任何东西。您可以在 catch 块中或仅在方法的末尾返回 null,具体取决于方法的目标是什么。

标签: java mysql jdbc arraylist


【解决方案1】:

不要在你的 try 范围内创建你的数组,而是在你的方法范围内创建它,在 try 之前并在你的程序结束时返回它,所以你可以使用这样的东西:

public ArrayList getData(String rule) {
    ArrayList emails = new ArrayList();//<<----create the list here
    try {
        String q = "select distinct email_id from logs where rule ='" + rule + "';";
        System.out.println(q);
        rs = st.executeQuery(q);
        //ArrayList emails = new ArrayList();<<--------don't create the list here
        while (rs.next()) {
            emails.add(rs.getString("email_id"));
        }
        //return emails;//<<-------don't return the result here
    } catch (Exception e) {
        System.out.println("" + e);
    }
    return emails;//<<-------return the list here
}

另一件事,为了避免任何语法错误或 SQL 注入,我建议改用 PreparedStatement,它更安全,更有帮助,例如:

public ArrayList getData(String rule) throws SQLException {
    ArrayList emails = new ArrayList();//
    try (PreparedStatement pstm = connection.prepareStatement(
            "select distinct email_id from logs where rule = ?")) {
        //NOTE: Position indexes start at 1, not 0
        pstm.setString(1, rule);
        ResultSet rs = pstm.executeQuery();
        while (rs.next()) {
            emails.add(rs.getString("email_id"));
        }
    }

    return emails;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多