How to connect to MySQL8 in a Java Maven project?

This article shows how to connect to a MySQL 8 database in a Java Maven project.

Posted on

To connect to a MySQL 8 database in a Java Maven project, you need to follow a specific set of steps to set up your project dependencies and establish the database connection. Here’s a step-by-step guide:

Step 1: Create a Maven Project

If you don’t already have a Maven project, you can create one using your preferred integrated development environment (IDE) or by running the following command in your terminal:

mvn archetype:generate -DgroupId=com.example \
    -DartifactId=mysql-connection-demo \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DinteractiveMode=false

This command generates a basic Maven project structure with a sample Java class.

Step 2: Add MySQL Connector/J Dependency

In your pom.xml file (located in the root of your Maven project), add the MySQL Connector/J dependency. Here’s an example of what your pom.xml might look like:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>mysql-connection-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- MySQL Connector/J -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version> <!-- Use the latest version available -->
        </dependency>
    </dependencies>
</project>

Make sure to replace 8.0.28 with the latest version of MySQL Connector/J if it has been updated.

Step 3: Create a Java Class for Database Connection

Create a Java class in the src/main/java/com/example directory (or the appropriate package for your project) for handling the database connection. Here’s an example of a simple Java class to establish a connection to a MySQL database:

package com.example;

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

public class DatabaseConnection {

    public static Connection getConnection() {
        Connection connection = null;
        try {
            String url = "jdbc:mysql://your_database_url:3306/your_database_name";
            String username = "your_username";
            String password = "your_password";
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Connected to the database!");
        } catch (SQLException e) {
            System.err.println("Connection error: " + e.getMessage());
        }
        return connection;
    }
}

Replace your_database_url, your_database_name, your_username, and your_password with your actual database information.

Step 4: Use the Database Connection

In your main application or any other Java class where you need to use the database connection, you can call the getConnection method from the DatabaseConnection class to obtain a connection object:

package com.example;

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

public class MyApp {
    public static void main(String[] args) {
        // Get a database connection
        Connection connection = DatabaseConnection.getConnection();

        // Use the connection to execute SQL queries and interact with the database
        try {
            // Your database operations here...
        } catch (SQLException e) {
            System.err.println("SQL error: " + e.getMessage());
        } finally {
            // Close the connection when done
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    System.err.println("Error closing connection: " + e.getMessage());
                }
            }
        }
    }
}

That’s it! You now have a Maven project set up to connect to a MySQL 8 database in Java. Make sure to handle exceptions properly, close the connection when done, and perform your database operations as needed.