It probably doesn't matter so much for embedded Derby databases because only the JVM that starts the server can obtain an embedded connection. But, it's always a good idiom to close resources like database connections when you're finished.
With Java 7 and above you can use the try-with-resources statement to do this for you automatically. For example:
import java.sql.*;
class DbConnect {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/";
String database = "database";
String userName = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(
url + database, userName, password)) {
System.out.println("Database connection: Successful");
// Do database work
} catch (Exception e) {
System.out.println("Database connection: Failed");
e.printStackTrace();
}
}
}
Here, the Connection
object will be automatically closed at the end of the block.
Note: you can use try-with-resources statements for any resources that implement java.lang.AutoCloseable
, for example when you're reading and writing files.