Java
MySQL
Database Connectivity
Programming
JDBC

Connect Java to a MySQL database

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Connecting a Java application to a MySQL database is a common requirement for many business and web applications. This process involves several steps, including setting up the MySQL environment, adding the MySQL JDBC driver to your project, and writing Java code to establish the connection and perform database operations.

Setting Up MySQL

Before you can connect to a MySQL database from a Java application, you need to have MySQL installed on your machine or have access to a MySQL server. You can download and install MySQL from its official website. Once MySQL is installed, create a database and a user with appropriate permissions:

  1. Log into MySQL as the root user:
 
   mysql -u root -p
  1. Create a new database:
 
   CREATE DATABASE exampledb;
  1. Create a user and grant privileges:
 
   CREATE USER 'javauser'@'localhost' IDENTIFIED BY 'password';
   GRANT ALL PRIVILEGES ON exampledb.* TO 'javauser'@'localhost';
   FLUSH PRIVILEGES;

Adding MySQL JDBC Driver

Java connects to databases using JDBC (Java Database Connectivity), which requires having the JDBC driver for MySQL. The JDBC driver for MySQL is called Connector/J. You can add this driver to your project by downloading the jar file from the MySQL website or, more conveniently, managing dependencies via Maven or Gradle.

  • Maven: Add the following dependency to your pom.xml:
xml
1  <dependency>
2      <groupId>mysql</groupId>
3      <artifactId>mysql-connector-java</artifactId>
4      <version>8.0.xx</version> <!-- Replace with the latest version -->
5  </dependency>
  • Gradle: Add the following line to your build.gradle:
gradle
  implementation 'mysql:mysql-connector-java:8.0.xx' // Replace with the latest version

Java Code to Connect MySQL

Once the JDBC driver is set up, you can write Java code to connect to the database. Here is a basic example of Java code connecting to a MySQL database:

java
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.SQLException;
4
5public class DatabaseConnector {
6    private static final String URL = "jdbc:mysql://localhost:3306/exampledb";
7    private static final String USER = "javauser";
8    private static final String PASSWORD = "password";
9
10    public static Connection connect() {
11        try {
12            // Register JDBC driver
13            Class.forName("com.mysql.cj.jdbc.Driver");
14            // Open a connection
15            return DriverManager.getConnection(URL, USER, PASSWORD);
16        } catch (ClassNotFoundException e) {
17            System.out.println("MySQL JDBC Driver not found.");
18            e.printStackTrace();
19        } catch (SQLException e) {
20            System.out.println("Connection to the database failed.");
21            e.printStackTrace();
22        }
23        return null;
24    }
25
26    public static void main(String[] args) {
27        Connection conn = connect();
28        if (conn != null) {
29            System.out.println("Successfully connected to the MySQL database.");
30            try {
31                conn.close();
32            } catch (SQLException ex) {
33                ex.printStackTrace();
34            }
35        }
36    }
37}

Handling Database Operations

After establishing the connection, you can perform SQL operations such as CREATE, READ, UPDATE, and DELETE. For example, you can execute a query to insert data or retrieve data using Statement or PreparedStatement interfaces:

java
1import java.sql.*;
2
3public class DatabaseOperations {
4    public static void insertData(Connection conn, String name, int age) {
5        String query = "INSERT INTO users(name, age) VALUES (?, ?)";
6        try (PreparedStatement pstmt = conn.prepareStatement(query)) {
7            pstmt.setString(1, name);
8            pstmt.setInt(2, age);
9            pstmt.executeUpdate();
10            System.out.println("Data inserted successfully.");
11        } catch (SQLException e) {
12            System.out.println("Error inserting data.");
13            e.printStackTrace();
14        }
15    }
16}

Key Points Summary

ComponentDescription
MySQL SetupInstall MySQL, create database and user.
JDBC DriverAdd MySQL Connector/J to the project.
ConnectionUse DriverManager.getConnection() to connect.
Database OpsPerform CRUD using Statement or PreparedStatement.

Conclusion

Connecting Java to a MySQL database involves preparatory steps such as setting up the database and configuring JDBC but provides robust options for database operations. Proper error handling and connection management (like using try-with-resources) enhance the efficiency and resilience of the application.


Course illustration
Course illustration

All Rights Reserved.