Personally, I like the second option, and this is how I imagine
public void addAccount(String username, String password, String name) {
String query="INSERT INTO Accounts (username, password, name) VALUES (?,?,?)";
try(Connection connection = dataSource.getConnection()) {
try(PreparedStatement statement = connection.preparedStatement(query)){
statement.setString(1, username);
statement.setString(2, password);
statement.setString(3, name);
statement.executeUpdate();
}
} catch(SQLException e) {
e.printStacktrace();
}
The reason you should use try-with-resource is only because it handles common coding errors such as closing if an error occurs. It also ensures that after execution your statement / connection / resultset will be closed (or any other problems)
source
share