我想知道以某种集合的形式返回结果集的正确方法是什么。 或者我应该创建同一类的类实例,然后返回它(如何做到这一点?) 这样做的常见做法是什么?或者我应该学习Hibernate并实现它?在java中返回查询结果集的正确方法
public class Author {
private String table_name = "authors";
int id;
String full_name;
String location;
int age;
String details;
/** Getter Setter Methods here ....*/
/** Constructor here.... */
/* Returns all Authors */
public ArrayList all() {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
/* TODO : figure out which collection is suitable .*/
DbHelper dbHelper = new DbHelper();
Connection conn = dbHelper.getConnection();
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
String query = "SELECT * FROM authors";
rs = stmt.executeQuery(query);
while (rs.next()) {
HashMap<String, String> hashmap = new HashMap<>();
int id = rs.getInt(1);
hashmap.put("id",rs.getString(1));
hashmap.put("full_name", rs.getString(2));
hashmap.put("location", rs.getString(3));
hashmap.put("age", rs.getString(4));
hashmap.put("details", rs.getString(5));
list.add(id,hashmap);
//hashmap.clear();
}
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("you are fuckt");
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
}
}
return list;
}
}
这取决于您的要求选择休眠或不...您对我们期望什么? – unknown