How to open and close JDBC connections

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):


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

Connection connection = DriverManager.getConnection(
        "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:


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:

If you liked this post, consider following me on Twitter and subscribing to Programming Brain on Youtube. Happy coding!

January 12, 2022


Popular Posts

Building a Kubernetes cluster on Raspberry Pi (with automation)

Some months ago, I was lucky enough to get a bunch of Raspberry Pi minicompute…

What is a Database Proxy?

A proxy is a server software, typically installed in a separate machine, that …

ChatGPT as a MariaDB database

ChatGPT is truly impressive. You can instruct it to do all sorts of things whe…

Recent Comments

Contact Me