I have this small project and I need to connect my Java application to the database. I have succeeded. I have few questions tho. I’m not sure how to handle resources. As of now I defaulted to packing as much as I can into try-wtith-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 reslutset both need to be closed. In first case I am using resultset 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? Is connection and resultset closed properly?
>Solution :
Yes, you have correctly used try-with-resources syntax to close your JDBC resources appropriately.
connection and reslutset both need to be closed
Yes.
- Both
Connection
andResultSet
classes are documented as having aclose
method that releases resources. So you should close them as early as is practical. - Both classes are documented as implementing
AutoCloseable
. So you can use them with try-with-resources syntax.