Connecting to MariaDB Server Using JDBC

Summary: in this tutorial, you will learn how to connect to the MariaDB server using the MariaDB’s JDBC Driver.

Downloading MariaDB JDBC driver

To connect to the MariaDB server, you need a JDBC driver provided by MariaDB.

The MariaDB Connector/J is a driver that implements standard JDBC API for developing Java applications that connect to the MariaDB server.

Open the page to download the latest version of MariaDB Connector/J driver.

The JDBC driver is a jar file such as mariadb-java-client-3.3.3.jar. You need to copy it to a specific directory for example: D:\mariadb-drivers\mariadb-java-client-3.3.3.jar

Creating a new project

First, launch the IntelliJ IDE.

Next, create a new project called sales.

Then, right-click the project name and choose the Open Module Settings.

After that, choose the Libraries under Project Settings and click New Project Library.

Finally, select the MariaDB Connector/J file such as D:\mariadb-drivers\mariadb-java-client-3.3.3.jar and click the OK button.

Creating a database configuration file

First, create a new file config.properties in the src directory of the project.

Second, add the following database configuration to the config.properties file:

db.url=jdbc:mariadb://localhost:3306/sales
db.username=bob
db.password=P@$$w0rd1Code language: Properties (properties)

The config.properties file includes three important parameters:

  • db.url: The URL to the MariaDB server. In this example, we connect to the local MariaDB server and port 3306, and the database sales.
  • db.user: The user account (bob) that connects to the MariaDB database.
  • db.password: The password for the user.

Notice you may need to replace these parameters with the one you use to connect to the MariaDB server.

Defining a Config class

First, create a new file in the src directory with the name Config.java.

Second, define the class Config in the Config.java file:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Config {

    private static final Properties properties = new Properties();

    static {
        try (var input = Config.class.getClassLoader().getResourceAsStream("config.properties")) {
            if (input == null) {
                System.out.println("Sorry, could not find the config.properties file");
                System.exit(1);
            }

            // Load the properties file
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDbUrl() {
        return properties.getProperty("db.url");
    }

    public static String getDbUsername() {
        return properties.getProperty("db.username");
    }

    public static String getDbPassword() {
        return properties.getProperty("db.password");
    }
}Code language: Java (java)

The Config class reads the database parameters from the config.properties file.

The Config includes three static methods that expose the database parameters:

  • getDbUrl() – Return the database URL.
  • getDbUsername() – Return the database username.
  • getDbPassword() – Return the database password.

Creating a DBConnection class

Create a new file named DBConnection.java file in the src directory and define the DBConnection class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBConnection {
    public static Connection connect() throws SQLException {

        try {
            // Register JDBC driver
            Class.forName("org.mariadb.jdbc.Driver");

            // Get database credentials from Config class
            var url = Config.getDbUrl();
            var user = Config.getDbUsername();
            var password = Config.getDbPassword();

            // Open a connection
            return DriverManager.getConnection(url, user, password);

        } catch (SQLException | ClassNotFoundException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
}
Code language: Java (java)

Creating a Java Program

The following defines the Main class that uses the DBConnection class to connect to the MariaDB database:

import java.sql.SQLException;

public class Main {
    public static void main(String[] args){
        try (var connection =  DBConnection.connect()){
            if(connection != null) System.out.println("Connected to the MariaDB database.");
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }
}Code language: Java (java)

The program connects to a MariaDB database using the Connection class.

It’ll display a success message if the connection is successful; otherwise, it displays an exception that occurred.

Notice that the program uses the try-with-resources to ensure that the Connection is closed properly, even when an exception occurs.

Connected to the MariaDB database.

Summary

  • Use the Connection object to connect to the MariaDB database.