JDBC CRUD with MySQL
STEP 1 · START HERE

Java + MySQL in One Small Project

In this codelab you will create a simple Java project, connect it to MySQL using JDBC, and perform the four basic database operations: Create, Read, Update, and Delete.

By the end: You will be able to create a Maven project, run it, connect Java to MySQL, insert a student, read students, update a student, and delete a student.
Java Application

Contains the JDBC code that sends SQL commands.

MySQL Database

Stores the student records.

CRUD means:

Create = INSERT, Read = SELECT, Update = UPDATE, Delete = DELETE.

What does CRUD describe?

STEP 2 · PREPARE THE DATABASE

Install MySQL and Create a Database

Before Java can connect to a database, MySQL must be installed and running.

macOS

brew install mysql
brew services start mysql

Ubuntu / Debian

sudo apt update
sudo apt install mysql-server
sudo systemctl start mysql

Windows

Install MySQL Community Server using the MySQL Installer. During setup, remember the password you choose for the root user.

Open MySQL

mysql -u root -p

Enter your MySQL root password when asked.

Create our database and table

CREATE DATABASE college;

USE college;

CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL
);

Check the table

SHOW TABLES;
DESCRIBE students;
Keep it simple:

We will use this same students table for every CRUD operation in the codelab.

STEP 3 · CREATE THE JAVA PROJECT

Create a Maven Quickstart Project

Maven gives us a standard Java project structure and makes adding the MySQL JDBC driver easy.

Check Java and Maven first

java -version
mvn -version

Create the project

Run this command in the folder where you want the project:

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

Open the project

cd jdbc-demo
jdbc-demo/ ├── pom.xml └── src/ ├── main/ │ └── java/ │ └── com/ │ └── example/ │ └── App.java └── test/
Main file:

For this codelab, we will write everything inside src/main/java/com/example/App.java.

STEP 4 · ADD JDBC DRIVER

Add MySQL Connector/J

Java needs the MySQL JDBC driver so JDBC knows how to communicate with a MySQL server.

Open pom.xml and replace it with this simple configuration:

Java version:

This codelab uses Java 21. The Maven compiler source and target are both set to 21.

<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
         https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

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

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <mainClass>com.example.App</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
What Maven does:

When the project runs, Maven downloads the MySQL JDBC driver automatically. You do not need to manually copy a JAR file into the project.

STEP 5 · TEST THE PROJECT

Run the Maven Project

Before adding database code, make sure the quickstart application runs correctly.

Open App.java and use:

package com.example;

public class App {
    public static void main(String[] args) {
        System.out.println("JDBC project is running!");
    }
}

Run it

mvn compile exec:java

You should see:

JDBC project is running!
IMPORTANT

If this step works, your Java + Maven project is ready. Only then continue to JDBC.

STEP 6 · CONNECT TO MYSQL

Open Your First JDBC Connection

Use DriverManager.getConnection() to connect Java to the college database.

package com.example;

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

/**
 * Hello world!
 *
 */
public class App {
    static final String URL = "jdbc:mysql://localhost:3306/college";

    static final String USER = "root";
    static final String PASSWORD = "";

    public static void main(String[] args) {

        try {
            Connection connection = DriverManager.getConnection(
                    URL, USER, PASSWORD);
            System.out.println("Connected to MySQL!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

This example assumes the local MySQL root user has an empty password. If your MySQL installation uses a password, put it in PASSWORD.

Run again

mvn compile exec:java

What does the Connection object represent?

STEP 8 · CREATE THE TABLE

Create the Students Table from Java

Before we can add, read, update, or delete students, the table must exist. We can create it directly from our Java program.

Goal: Write a createTable() function that runs a CREATE TABLE IF NOT EXISTS query.

Create the function

static void createTable() {

    String sql =
            "CREATE TABLE IF NOT EXISTS students (" +
            "id INT PRIMARY KEY AUTO_INCREMENT, " +
            "name VARCHAR(100), " +
            "email VARCHAR(100)" +
            ")";

    try {
        PreparedStatement statement =
                connection.prepareStatement(sql);

        statement.executeUpdate();

        System.out.println("Students table is ready!");

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Why use IF NOT EXISTS?

If the table already exists, MySQL will not throw an error. This makes the program safe to run again.

Call it after connecting

connection = DriverManager.getConnection(
        URL, USER, PASSWORD);

System.out.println("Connected to MySQL!");

createTable();
Flow:

Connect to MySQL → create the table if needed → start CRUD operations.

Why do we use CREATE TABLE IF NOT EXISTS?

STEP 7 · CRUD: CREATE

Insert a Student

For Create, we use SQL INSERT. Use PreparedStatement and placeholders instead of building SQL strings manually.

SQL we want to run

INSERT INTO students (name, email)
VALUES (?, ?)

Java method

static void createStudent(
        Connection connection,
        String name,
        String email) {

    String sql = "INSERT INTO students (name, email) VALUES (?, ?)";

    try {
        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setString(1, name);
        statement.setString(2, email);

        int rows = statement.executeUpdate();

        System.out.println(rows + " student inserted.");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Call it from main()

createStudent(
    connection,
    "Aman",
    "aman@example.com"
);
Remember:

executeUpdate() is used for INSERT, UPDATE, and DELETE. It returns the number of affected rows.

STEP 8 · CRUD: READ

Read Students with ResultSet

For Read, use SQL SELECT. The returned rows are available through a ResultSet.

static void readStudents(Connection connection) {

    String sql = "SELECT id, name, email FROM students";

    try {
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();

        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String email = resultSet.getString("email");

            System.out.println(id + " | " + name + " | " + email);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Call it

readStudents(connection);
The only ResultSet idea you need here:

next() moves to the next row. Then use methods such as getInt() and getString() to read columns.

Which method should we use for SELECT?

STEP 9 · CRUD: UPDATE

Update a Student

Use SQL UPDATE when an existing record needs to change.

static void updateStudent(
        Connection connection,
        int id,
        String newName,
        String newEmail) {

    String sql = "UPDATE students SET name = ?, email = ? WHERE id = ?";

    try {
        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setString(1, newName);
        statement.setString(2, newEmail);
        statement.setInt(3, id);

        int rows = statement.executeUpdate();

        System.out.println(rows + " student updated.");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Call it

updateStudent(
    connection,
    1,
    "Aman Sharma",
    "aman.sharma@example.com"
);
WATCH THE WHERE

WHERE id = ? tells MySQL which student to update. Without a WHERE condition, an UPDATE can change every row.

STEP 10 · CRUD: DELETE

Delete a Student

Use SQL DELETE to remove an existing record.

static void deleteStudent(Connection connection, int id) {

    String sql = "DELETE FROM students WHERE id = ?";

    try {
        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setInt(1, id);

        int rows = statement.executeUpdate();

        System.out.println(rows + " student deleted.");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Call it

deleteStudent(connection, 1);
Be careful:

Just like UPDATE, DELETE should normally have a WHERE condition. DELETE FROM students would remove every student.

STEP 12 · PUT EVERYTHING TOGETHER

Complete CRUD Program with CLI Menu

Now we will keep the CRUD functions we already wrote and simply call them from a menu inside main().

Goal: Use one Java program. The CRUD logic stays inside functions such as createStudent(), readStudents(), updateStudent(), and deleteStudent(). The CLI only decides which function to call.

CLI menu

1. Add Student
2. Read Students
3. Update Student
4. Delete Student
5. Exit

Complete program

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class App {

    static final String URL = "jdbc:mysql://localhost:3306/college";
    static final String USER = "root";
    static final String PASSWORD = "";

    static Connection connection;
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        try {
            connection = DriverManager.getConnection(
                    URL, USER, PASSWORD);

            System.out.println("Connected to MySQL!");

            createTable();

            boolean running = true;

            while (running) {

                System.out.println();
                System.out.println("===== STUDENT MENU =====");
                System.out.println("1. Add Student");
                System.out.println("2. Read Students");
                System.out.println("3. Update Student");
                System.out.println("4. Delete Student");
                System.out.println("5. Exit");
                System.out.print("Enter your choice: ");

                int choice = scanner.nextInt();
                scanner.nextLine();

                switch (choice) {

                    case 1:
                        createStudent();
                        break;

                    case 2:
                        readStudents();
                        break;

                    case 3:
                        updateStudent();
                        break;

                    case 4:
                        deleteStudent();
                        break;

                    case 5:
                        running = false;
                        break;

                    default:
                        System.out.println("Invalid choice.");
                }
            }

            System.out.println("Program closed.");

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

    static void createTable() {

        String sql =
                "CREATE TABLE IF NOT EXISTS students (" +
                "id INT PRIMARY KEY AUTO_INCREMENT, " +
                "name VARCHAR(100), " +
                "email VARCHAR(100)" +
                ")";

        try {
            PreparedStatement statement =
                    connection.prepareStatement(sql);

            statement.executeUpdate();

            System.out.println("Students table is ready!");

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

    static void createStudent() {

        System.out.print("Enter student name: ");
        String name = scanner.nextLine();

        System.out.print("Enter student email: ");
        String email = scanner.nextLine();

        String sql =
                "INSERT INTO students (name, email) VALUES (?, ?)";

        try {
            PreparedStatement statement =
                    connection.prepareStatement(sql);

            statement.setString(1, name);
            statement.setString(2, email);

            int rows = statement.executeUpdate();

            System.out.println(rows + " student added.");

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

    static void readStudents() {

        String sql =
                "SELECT id, name, email FROM students";

        try {
            PreparedStatement statement =
                    connection.prepareStatement(sql);

            ResultSet resultSet =
                    statement.executeQuery();

            System.out.println();
            System.out.println("ID | NAME | EMAIL");
            System.out.println("-----------------------------");

            while (resultSet.next()) {

                int id = resultSet.getInt("id");
                String name =
                        resultSet.getString("name");
                String email =
                        resultSet.getString("email");

                System.out.println(
                        id + " | " + name + " | " + email
                );
            }

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

    static void updateStudent() {

        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine();

        System.out.print("Enter new name: ");
        String name = scanner.nextLine();

        System.out.print("Enter new email: ");
        String email = scanner.nextLine();

        String sql =
                "UPDATE students SET name = ?, email = ? WHERE id = ?";

        try {
            PreparedStatement statement =
                    connection.prepareStatement(sql);

            statement.setString(1, name);
            statement.setString(2, email);
            statement.setInt(3, id);

            int rows = statement.executeUpdate();

            System.out.println(rows + " student updated.");

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

    static void deleteStudent() {

        System.out.print("Enter student ID: ");
        int id = scanner.nextInt();
        scanner.nextLine();

        String sql =
                "DELETE FROM students WHERE id = ?";

        try {
            PreparedStatement statement =
                    connection.prepareStatement(sql);

            statement.setInt(1, id);

            int rows = statement.executeUpdate();

            System.out.println(rows + " student deleted.");

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

How this version is structured

main()

Connects to MySQL, calls createTable(), then shows the CLI menu.

createTable()

Creates the students table if it does not already exist.

createStudent()

Handles INSERT.

readStudents()

Handles SELECT and ResultSet.

updateStudent()

Handles UPDATE.

deleteStudent()

Handles DELETE.

Important:

The CLI is not a second CRUD program. It is only the menu layer that calls the CRUD functions we already created.

Run the program

mvn compile exec:java

Test the full CRUD flow

  1. Choose 1 and add a student.
  2. Choose 2 and verify the student appears.
  3. Choose 3 and update the same student.
  4. Choose 2 again and verify the changes.
  5. Choose 4 and delete the student.
  6. Choose 2 once more and confirm the student is gone.
  7. Choose 5 to exit.

What does main() do in this program?

STEP 13 · REVISION

Remember These JDBC Basics

For a beginner CRUD application, these are the important ideas to remember.

TaskSQLJDBC method
CreateINSERTexecuteUpdate()
ReadSELECTexecuteQuery() → ResultSet
UpdateUPDATEexecuteUpdate()
DeleteDELETEexecuteUpdate()
What is JDBC?
JDBC is the standard Java API used to communicate with relational databases.
What is Connection?
It represents the active connection between the Java application and the database.
Why use PreparedStatement?
It lets us write SQL with placeholders and pass values separately. This is safer and easier than concatenating values into SQL strings.
What is ResultSet?
It contains rows returned by a SELECT query. Use next() to move through those rows.
executeQuery() vs executeUpdate()?
Use executeQuery() for SELECT. Use executeUpdate() for INSERT, UPDATE, and DELETE.

Completion checklist

  • I can create a Maven quickstart project.
  • I can run the project with Maven.
  • I can add the MySQL JDBC driver.
  • I can connect Java to MySQL.
  • I can INSERT a record.
  • I can SELECT records using ResultSet.
  • I can UPDATE a record.
  • I can DELETE a record.
  • I can create the students table from Java.
  • I can connect the CRUD functions to a simple CLI menu.

Codelab complete! 🎉

You can now build one Java JDBC program that performs CRUD operations through a simple CLI menu.