Skip to main content

How to open and close JDBC connections

·153 words·1 min
Programming Databases
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and award winner. He currently works for MariaDB plc as a Developer Relations Engineer. Starting his coding journey at 13 with BASIC on a rudimentary black screen, Alejandro quickly transitioned to C, C++, and Java during his academic years at the National University of Colombia. Relocating first to the UK and then to Finland, Alejandro deepened his involvement in the open-source community. He’s a recognized figure in Java circles, credited with articles and videos amassing millions of views, and presentations at international events.

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:

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

Related

Testing MariaDB ColumnStore performance
·1288 words·7 mins
SQL Databases
MariaDB’s ColumnStore is an engine that stores data in a columnar fashion.
Using Vaadin web components in HTML documents without frameworks
·525 words·3 mins
Programming Vaadin UI
Vaadin is a development platform for building web applications in Java.
How to start a career in coding
·1737 words·9 mins
Programming
A couple of days ago, a good friend of mine asked me how to make her kid more interested in programming.