Statements prepared by Java in try with resources do not work properly
See English answers > how should I use try with resources with JDBC? 4
What on earth did I do wrong? Or is it impossible? This is my code:
try (Connection conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ? LIMIT 1");
stmt.setInt(1,user);
ResultSet rs = stmt.executeQuery()) {
// if no record found
if(!rs.isBeforeFirst()) {
return false;
}
// if record found
else {
return true;
}
} catch (sqlException e) {
// log error but dont do anything,maybe later
String error = "sqlException: " + e.getMessage() + "\nsqlState: " + e.getsqlState() + "\nVendorError: " + e.getErrorCode();
return false;
}
Solution
The try with resource statement is used to declare (autoclosable) resources Connection, Preparedstatement and resultset are autoclosable, so it doesn't matter
But stmt Setint (1, user) is not a resource, but a simple statement You cannot have a simple statement (not a resource declaration) in a try with resource statement!
Solution: create multiple try with resource statements!
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
}
}
}
(please note that technically, you don't need to put the execution of SQL statements into a separate method like me. If opening a connection and creating a Preparedstatement are in the same try with resource statement, it can also work. I only consider the good practice of separating the connection management content from the rest of the code
