I have this small project and I need to connect my Java application to the database. I have succeeded. I have few questions though. I'm not sure how to handle resources. As of now, I defaulted to packing as much as I can into try-with-resources because, it is reliable option for closing them automatically. But I'm not 100% sure if I'm doing it right.
There are 2 cases:
- I use function
ResultSet executeQuery(String sql)
try
(
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)
)
{
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
String number = new String();
while (resultSet.next()) {
for (int i = 1; i <= columnsNumber; i++) {
number = resultSet.getString(i);
}
}
retValue = Integer.parseInt(number);
…
}
- I use function
int executeUpdate(String sql)
try
(
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()
)
{
statement.executeUpdate(query);
…
}
From what I understand, Connection and ResultSet both need to be closed. In first case I am using result set later, so that's why I'm creating a variable in () of try. But in the second case executeUpdate cannot be put in (). I know that it returns int, but I am still unsure. Is this sufficient? Are connection and result set closed properly?
Yes, correct
Yes, you have correctly used try-with-resources syntax to close your JDBC resources appropriately.
You said:
Yes.
ConnectionandResultSetclasses are documented as having aclosemethod that releases resources. So you should close them as early as is practical.AutoCloseable. So you can use them with try-with-resources syntax.Ditto for
java.sql.Statement.In contrast, look at the
ResultSetMetaDataclass. That class has noclosemethod, and does not implementAutoCloseable. So that class, unlike a regularResultSet, does not need to be closed, and cannot be used in try-with-resources syntax.AutoCloseableYou said:
The
executeUpdatemethod does not return anAutoCloseableobject. So that method cannot be called with try-with-resources syntax.That method
executeUpdatereturns a primitiveintrather than a reference to an object. So there is noclosemethod to call.