Steps for Connecting to MySQL Database in Java: A Complete Guide

8/16/2025

#Steps for Connecting MySQL Database in Java: A Complete Guide

Go Back

Steps for Connecting to MySQL Database in Java: A Complete Guide


Introduction

When building Java applications, connecting to a MySQL database is one of the most common requirements. Java provides JDBC (Java Database Connectivity), an API that enables applications to connect and interact with relational databases such as MySQL.

In this article, you’ll learn the step-by-step process to connect to MySQL in Java, including setup, coding examples, and best practices.


#Steps for Connecting  MySQL Database in Java: A Complete Guide

Prerequisites

Before connecting Java to MySQL, ensure you have:

  • Java Development Kit (JDK) installed

  • MySQL Server installed

  • MySQL Connector/J (JDBC Driver) downloaded and added to your project classpath

  • A sample database (e.g., testdb) with a table (e.g., users)


Steps to Connect MySQL Database in Java

Step 1: Import JDBC Packages

Import the required JDBC classes:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

Step 2: Load and Register JDBC Driver

Load the MySQL JDBC Driver:

Class.forName("com.mysql.cj.jdbc.Driver");

Step 3: Establish Connection

Create a connection using DriverManager:

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

Step 4: Create Statement

Use the connection object to create a statement:

Statement stmt = con.createStatement();

Step 5: Execute SQL Query

Execute a query to fetch data from the database:

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Step 6: Process the Result Set

Iterate through the results:

while (rs.next()) {
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
}

Step 7: Close the Connection

Always close the connection to free resources:

con.close();

Complete Example: Connecting Java to MySQL

import java.sql.*;

public class MySQLConnectionDemo {
    public static void main(String[] args) {
        try {
            // Step 1: Load and register JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Establish connection
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "password");

            // Step 3: Create statement
            Statement stmt = con.createStatement();

            // Step 4: Execute query
            ResultSet rs = stmt.executeQuery("SELECT * FROM users");

            // Step 5: Process results
            while (rs.next()) {
                System.out.println(rs.getInt(1) + " " + rs.getString(2));
            }

            // Step 6: Close connection
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output: Displays data from the users table in the testdb database.


Best Practices

  • Always close the connection, statement, and result set.

  • Use PreparedStatement instead of Statement to avoid SQL injection.

  • Store database credentials securely.

  • Use connection pooling for high-performance applications.


Conclusion

By following these steps, you can easily connect a Java program to a MySQL database using JDBC. Mastering JDBC connections is a key step toward building database-driven Java applications. With best practices like connection pooling and prepared statements, your applications will be secure, scalable, and efficient.


🔑 Target SEO Keywords:
Connect MySQL in Java, JDBC MySQL connection, MySQL Java example, JDBC MySQL tutorial, MySQL database connection steps, JDBC connection in Java, Java MySQL driver.

Table of content