try-with-resource语句用于声明(Autoclosable)资源. Connection,PreparedStatement和ResultSet是Autoclosable,所以没关系.
但是stmt.setInt(1,user)不是资源,而是一个简单的语句.在try-with-resource语句中不能有简单的语句(不是资源声明)!
解决方案:创建多个try-with-resource语句!
try (Connection conn = DriverManager.getConnection(DBURL,DBPASS)) {
executeStatement(conn);
} catch (sqlException e) {
// log error but dont do anything,maybe later
String error = "sqlException: " + e.getMessage() + "\nsqlState: " + e.getsqlState() + "\nVendorError: " + e.getErrorCode();
return false;
}
private void executeStatement(Connection con) throws sqlException {
try (PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id=? LIMIT 1")) {
stmt.setInt(1,user);
try (ResultSet rs = stmt.executeQuery()) {
// process result
}
}
}
(请注意,从技术上讲,不需要像我一样将sql语句的执行放入单独的方法中.如果打开连接和创建PreparedStatement都在同一个try-with-resource语句中,它也可以工作.我只考虑将连接管理内容与其余代码分开的良好做法.