Connecting to MySQL Using JDBC Driver

Summary: in this tutorial, you will learn how to connect to the MySQL database using the JDBC Connection object.

This tutorial picks up where the Setting Up MySQL JDBC Development Environment tutorial left off.

Creating a new project

First, launch the IntelliJ IDE.

Second, create a new project called mysql-jdbc.

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

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

Fifth, select the mysql connector file such as D:\mysql-drivers\mysql-connector-j-8.2.0\mysql-connector-j-8.2.0.jar and click OK.

Creating a database configuration file

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

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

db.url=jdbc:mysql://localhost:3306/mysqljdbc
db.username=<user>
db.password=<password>Code language: Properties (properties)

In this config.properties, we specify three important pieces of information:

  • db.url: The URL to the MySQL server. In this example, we connect to the local MySQL server and port 3306, database mysqljdbc.
  • db.user: The user account that connects to the database.
  • db.password: The password for the user.

Note that you need to replace the user and password with the one that you use to connect to the MySQL server.

Defining a DatabaseConfig class

First, create a new file in the src directory called DatabaseConfig.java.

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

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

public class DatabaseConfig {

    private static final Properties properties = new Properties();

    static {
        try (InputStream input = DatabaseConfig.class.getClassLoader().getResourceAsStream("config.properties")) {
            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                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 DatabaseConfig class reads the database configuration from the config.properties file.

The DatabaseConfig has three static methods that expose the database configuration:

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

Creating a MySQLConnection class

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

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


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

        try {
            // Register JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

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

            // Open a connection
            return DriverManager.getConnection(jdbcUrl, 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 MySQLConnection class to connect to the MySQL database:

import java.sql.SQLException;

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

The program connects to a MySQL database using the MySQLConnection class.

If the connection is successful, it prints a success message; otherwise, it catches and displays any SQLException that might occur during the connection process.

Note that we use the try-with-resources to ensure that the Connection is closed properly, even if an exception occurs.

The output of the program if it successfully connects to the MySQL server:

Connected to the MySQL database.

Summary

  • Use the Connection object to connect to the MySQL database.
Was this tutorial helpful?