Java with MySQL Connection

Introduction

Java applications often need to store and retrieve data from databases. One of the most popular databases used with Java is MySQL, an open-source relational database management system (RDBMS). Java communicates with MySQL using JDBC (Java Database Connectivity), a standard API that enables Java applications to execute SQL statements and interact with databases.

Connecting Java to MySQL is one of the first practical steps in developing database-driven applications such as banking systems, e-commerce websites, employee management systems, and student information systems.

What is Java with MySQL Connection?

Java with MySQL Connection is the process of establishing communication between a Java application and a MySQL database using the JDBC API and the MySQL JDBC Driver (MySQL Connector/J).

Once the connection is established, the Java application can:

  • Insert records
  • Retrieve records
  • Update existing records
  • Delete records
  • Execute SQL queries
  • Call stored procedures
  • Manage database transactions

Prerequisites

Before connecting Java with MySQL, ensure you have the following installed:

  • Java Development Kit (JDK)
  • MySQL Server
  • MySQL Workbench (optional but recommended)
  • MySQL Connector/J (JDBC Driver)
  • Any Java IDE (IntelliJ IDEA, Eclipse, NetBeans, or VS Code)

JDBC Components Required

The following JDBC classes and interfaces are commonly used:

Component Purpose
DriverManager Establishes the database connection
Connection Represents the active database connection
Statement Executes SQL statements
PreparedStatement Executes parameterized SQL queries
ResultSet Stores the data returned from SELECT queries
SQLException Handles database-related exceptions

Step 1: Create a MySQL Database

First, create a database.


CREATE DATABASE company;

Use the database.


USE company;

Step 2: Create a Table

Create an Employee table.


CREATE TABLE employee(
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(50),
    salary DOUBLE
);

Insert some sample records.


INSERT INTO employee VALUES
(101,'Rahul','IT',55000),
(102,'Amit','HR',42000),
(103,'Neha','Finance',60000);

Step 3: Add MySQL JDBC Driver

Download MySQL Connector/J from the official MySQL website and add the JAR file to your Java project’s classpath.

If you are using Maven, add the following dependency.


<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.3.0</version>
</dependency>

For Gradle:


implementation 'com.mysql:mysql-connector-j:9.3.0'

Step 4: JDBC Connection URL

The general syntax is:


jdbc:mysql://hostname:port/databaseName

Example:


jdbc:mysql://localhost:3306/company

Where:

  • localhost → Database server
  • 3306 → Default MySQL port
  • company → Database name

Step 5: Establish Connection

Use the DriverManager class to create the connection.


Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/company",
    "root",
    "password"
);

Parameters:

  • Database URL
  • Username
  • Password

If the credentials are correct, a connection is established successfully.

Complete Java with MySQL Connection Example


import java.sql.Connection;
import java.sql.DriverManager;
public class MySQLConnectionExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/company";
        String username = "root";
        String password = "password";
        try {
            Connection con = DriverManager.getConnection(
                    url,
                    username,
                    password);
            System.out.println("Connected Successfully!");
            con.close();
        } catch (Exception e) {
            e.printStackTrace()
        }
    }
}

Output

Connected Successfully!

Reading Data from MySQL

The following example retrieves all employee records.


import java.sql.*;
public class SelectExample 
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/company";
        String user = "root";
        String password = "password";
        try {
            Connection con = DriverManager.getConnection(url, user, password);
            String sql = "SELECT * FROM employee";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(
                        rs.getInt("id") + " " +
                        rs.getString("name") + " " +
                        rs.getString("department") + " " +
                        rs.getDouble("salary")
                );
            }
            rs.close();
            ps.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output

101 Rahul IT 55000.0
102 Amit HR 42000.0
103 Neha Finance 60000.0

Understanding the Code

DriverManager

Creates a database connection.


DriverManager.getConnection(...)

Connection

Represents the connection between Java and MySQL.


  Connection con

PreparedStatement

Executes SQL statements securely and efficiently.


PreparedStatement ps

ResultSet

Stores rows returned by a SELECT query.


ResultSet rs

close()

Closes database resources and releases memory.


con.close();

JDBC Connection Workflow


  Java Application
        │
        ▼
  DriverManager
        │
        ▼
    Connection
        │
        ▼
 PreparedStatement
        │
        ▼
 MySQL Database
        │
        ▼
   ResultSet
        │
        ▼
Java Application

Real-life Example

Suppose you are developing an Employee Management System.

When the HR manager clicks View Employees, the following steps occur:

  1. The Java application receives the request.
  2. JDBC establishes a connection with MySQL.
  3. A SQL query is executed to fetch employee details.
  4. MySQL returns the matching records.
  5. Java reads the ResultSet.
  6. The employee information is displayed on the screen.

Similarly, Java applications use MySQL connections in:

  • Online Banking Systems
  • Hospital Management Systems
  • School Management Systems
  • E-commerce Websites
  • Library Management Systems
  • Hotel Reservation Systems

Advantages of Connecting Java with MySQL

  • Easy to learn and implement
  • Platform independent
  • Fast database communication
  • Supports CRUD operations
  • Secure when using PreparedStatement
  • Supports transactions
  • Works with all major Java frameworks
  • Reliable for enterprise applications
  • Open-source database with large community support

Best Practices

Follow these recommendations while working with Java and MySQL:

📖
Best Practices:
  • Always use PreparedStatement instead of Statement.
  • Close Connection, PreparedStatement, and ResultSet after use.
  • Use try-with-resources to automatically manage resources.
  • Never hardcode database credentials in production applications.
  • Store credentials in configuration files or environment variables.
  • Use connection pooling (such as HikariCP) for better performance.
  • Handle SQLException properly.
  • Validate user input before executing database operations.

Common Mistakes

Beginners frequently encounter these issues:

  • Forgetting to add the MySQL JDBC Driver.
  • Using an incorrect JDBC URL.
  • Entering the wrong username or password.
  • Not closing database resources.
  • Using Statement instead of PreparedStatement.
  • Ignoring SQL exceptions.
  • Hardcoding sensitive database credentials.
  • Forgetting to create the database or table before running the program.

Conclusion

Connecting Java with MySQL is a fundamental skill for developing database-driven applications. Using JDBC, Java applications can securely communicate with MySQL to perform CRUD operations, execute SQL queries, and manage transactions. By understanding the connection process, configuring the JDBC driver correctly, and following best practices such as using PreparedStatement and closing resources properly, developers can build efficient, secure, and scalable applications.

Related Java Tutorials