gpt4 book ai didi

java - 在方法内关闭数据库相关资源

转载 作者:行者123 更新时间:2023-11-29 07:46:47 25 4
gpt4 key购买 nike

@Joeblade 建议我将数据库连接逻辑移动到一个单独的方法(如果不是单独的类),因为用户界面类已经非常困惑,包含大量用户界面代码,因此添加数据库无助于可读性对其进行编码。如果我需要的话,这也将有助于重用数据库代码。我做到了。但现在,我的问题是关于关闭资源。

static Connection getConnection() {
return connection;
}

public ResultSet Execute_Query(String queryIn) throws SQLException {
ResultSet resSet = null;
try {
connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
resSet = stmt.executeQuery(queryIn);
} catch (SQLException e) {
e.printStackTrace();
}
return resSet;
}

public String textForLabel() throws SQLException{

List<Float> floatArrayList = new ArrayList<Float>();

String query ="SELECT f.Flat, f.Mobile, f.Food, f.Alcohol, f.Transport, f.Outdoor, f.Pauls_stuff, f.Stuff FROM finance.fin f WHERE f.tbl_Date >= DATE_FORMAT( NOW( ) , '%Y-%m-10' ) + INTERVAL IF( DAY( NOW( ) ) >10, 0 , -1 ) MONTH AND f.tbl_Date <= CURDATE( ) ";

try {
ResultSet rs = null;
rs = Execute_Query(query);

while (rs.next()){
floatArrayList.add(rs.getFloat("Flat"));
floatArrayList.add(rs.getFloat("Mobile"));
floatArrayList.add(rs.getFloat("Food"));
floatArrayList.add(rs.getFloat("Alcohol"));
floatArrayList.add(rs.getFloat("Transport"));
floatArrayList.add(rs.getFloat("Outdoor"));
floatArrayList.add(rs.getFloat("Pauls_stuff"));
floatArrayList.add(rs.getFloat("Stuff"));
}
} catch(SQLException ee){
ee.printStackTrace();
}
// Irrelevant stuff down below.....
  1. 我是否必须在 Execute_Query() 方法中关闭 Connection、Statement、ResultSet 并在 textForLabel() 方法中(仅)关闭 ResultSet?
  2. 如何使用 try-with-resources 功能来关闭此操作?

最佳答案

尝试这样的事情

} catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
}

finally 语句将确保“connection.close();”即使代码抛出异常也会被调用。

关于java - 在方法内关闭数据库相关资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27534178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com