在java中给出错误返回类型的错误

时间:2017-05-30 10:54:11

标签: java mysql jdbc arraylist

我正在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类型的结果" ..但我正在返回'电子邮件& #39;只有ArrayList类型..帮我弄清楚这个错误..

1 个答案:

答案 0 :(得分:1)

不要在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;
}