-1

I am building an application that needs to regularly access an internal Apache Derby database.

I am wondering if I should be closing the applications connection after every set of statements is complete or if I can leave the connection open.

The application will only be used and accessed by one user at any given time.

Would your answer change if I was using an external database?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • found some information here https://stackoverflow.com/questions/11356937/good-practice-to-open-close-connections-in-an-asp-net-application but it doesn't fully answer my question. Any comments are appreciated. – Third Partition Development May 26 '18 at 06:47
  • embedded configuration? client-server configuration? How many connections are you planning to have open at once: tens? hundreds? thousands? What do you mean by "using an external database"? – Bryan Pendleton May 29 '18 at 01:20

1 Answers1

0

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.

craigcaulfield
  • 3,381
  • 10
  • 32
  • 40