1 回答
TA贡献1840条经验 获得超5个赞
你基本上有3个选择:
不要关闭方法中的
ResultSet
,Statement
和Connection
,将执行此操作的责任移交给调用者。不推荐,因为它容易出错,并且会破坏格式良好的代码结构范例。
按照Jacob G.的建议,传入具有处理数据所需逻辑的对象。
例如使用 Java 8+
Consumer
:
public static void queryDB(String query, Consumer<ResultSet> processor) {
try (
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
) {
processor.accept(resultSet);
} catch (SQLException ex) {
Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
}
}
然后像这样调用它:
SQLInterp.queryDB("SELECT * FROM foo", rs -> {
while (rs.next()) {
// process data here
}
});
以通用数据结构将所有数据读入内存,例如List<Map<String, Object>>:
这当然假设查询对每一列都有很好的唯一名称。
public static List<Map<String, Object>> queryDB2(String query) {
try (
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
) {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
String[] name = new String[columnCount];
for (int i = 0; i < columnCount; i++)
name[i] = metaData.getColumnLabel(i + 1);
List<Map<String, Object>> rows = new ArrayList<>();
while (resultSet.next()) {
Map<String, Object> row = new LinkedHashMap<>();
for (int i = 0; i < columnCount; i++)
row.put(name[i], resultSet.getObject(i + 1));
rows.add(row);
}
return rows;
} catch (SQLException ex) {
Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
}
}
添加回答
举报