我正在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
类型..帮我弄清楚这个错误..
答案 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;
}