I'm working on a small web app that will use a MySQL DB, with several servlets doing different kinds of SQL - insert, update, delete, etc. Before, I used to write a separate class Database.java, with a separate function for each query. However, this builds up a large and messy file, and now I would like to make generic functions, such as this one:
static ArrayList rs(String query, List params, int columns) {
ArrayList result = new ArrayList();
Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;
try {
con = getConnection();
stmt = con.prepareStatement(query);
for (int i = 0; i < params.size(); i++) {
stmt.setObject(i+1, params.get(i));
}
rs = stmt.executeQuery();
while(rs.next()) {
ArrayList thisRow = new ArrayList();
for (int column = 1; column <= columns; column++) {
thisRow.add(rs.getObject(column));
}
result.add(thisRow);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
Is this good/bad, efficient/inefficient way of doing things? Are there better ways to achieve what I need? I've read something about "JPA", however, I have no understanding of how it works or is used, and would like the queries to be as generic as possible (typeless and with any number of parameters).