Skip to main content

How to open and close JDBC connections

·134 words·1 min
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and Developer Relations Engineer at MariaDB. He has been programming computers since the mid-90s. Starting with BASIC, Alejandro transitioned to C, C++, and Java during his academic years at the National University of Colombia. He relocated first to the UK and then to Finland to foster his involvement in the open-source industry. Alejandro is a recognized figure in Java and MariaDB circles.

To open and close database connections in Java, get a JDBC driver for your database. For example, in the case of MariaDB databases, you can add the following to the pom.xml file (or download the JAR and manually add it to your project if you are not using a tool like Maven):

<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>LATEST</version>
</dependency>

Use a try-with-resources block to get a Connection object:

Connection connection = DriverManager.getConnection(
        "jdbc:mariadb://localhost:3306/database\_name",
        "user", "password"
);

If for some reason you cannot use a try-with-resources block, remember to close the connection, ideally in a finally block to guarantee that the connection is closed even if an exception is thrown:

connection.close();

See JDBC Tutorial Part 1: Connecting to a Database, for a more detailed tutorial or watch me coding an example Java application from scratch using JDBC:

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Related