I want to use try with resources, though my program can not fulfill operations after connection is closed.
String conn = "jdbc:mysql://localhost:3306/test?&serverTimeZone=Europe/Moscow&useSSL=false&allowPublicKeyRetrieval=true";
try (Connection connection = DriverManager.getConnection( conn,"root","admin"))
{
return connection;
} catch (SQLException e) {
throw new RuntimeException(e);
}
My project is https://github.com/anatoliy19/1.1.3.git
The resource allocated in the try-with-resources block is closed when you leave the block. So when you return the connection, that connection is closed. The reference to the connection is still valid though and will not be GCed until it is no longer referenced.
You can think of it this way. If the connection returned here was not closed, when would the compiler know that it should close it? The compiler can not know that.
You should use the connection inside that block or manage closing the connection yourself and not use try-with-resources.