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

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


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

Databases
January 12, 2022
0

Search

Popular Posts

How to call a Java method from a JavaScript function in the browser

In this video I demonstrate how to call a Java method that runs in the server f…

Testing MariaDB ColumnStore performance

MariaDB 's ColumnStore is an engine that stores data in a columnar fashion…

New YouTube channel on Programming (mostly Java)

Recently, I joined MariaDB Corporation as a Developer Advocate. My job is to h…

Recent Comments

Contact Me