在Springboot 中使用线程池ExecutorService,在线程池并发执行的任务中使用预编译、ResultSet,要怎么处理关闭的 Resultset: getObject这个异常,应该在run()中定义 Resultset使用完后关闭吗
时间: 2024-03-01 13:55:26 浏览: 12
在使用线程池ExecutorService时,如果在任务中使用了预编译语句和ResultSet,需要确保在任务执行完毕后及时关闭ResultSet。
可以将ResultSet定义为局部变量,并在使用完毕后在finally块中关闭。例如:
```java
public void run() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM user WHERE id = ?");
ps.setInt(1, 1);
rs = ps.executeQuery();
while (rs.next()) {
// do something
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这样可以确保ResultSet在任务执行完毕后被正确关闭,避免getObject这个异常。