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.
Contains the JDBC code that sends SQL commands.
Stores the student records.
Create = INSERT, Read = SELECT, Update = UPDATE, Delete = DELETE.
What does CRUD describe?
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 mysqlUbuntu / Debian
sudo apt update
sudo apt install mysql-server
sudo systemctl start mysqlWindows
Install MySQL Community Server using the MySQL Installer. During setup, remember the password you choose for the root user.
Open MySQL
mysql -u root -pEnter 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;We will use this same students table for every CRUD operation in the codelab.
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 -versionCreate 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=falseOpen the project
cd jdbc-demoFor this codelab, we will write everything inside src/main/java/com/example/App.java.
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:
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>When the project runs, Maven downloads the MySQL JDBC driver automatically. You do not need to manually copy a JAR file into 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:javaYou should see:
JDBC project is running!If this step works, your Java + Maven project is ready. Only then continue to JDBC.
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:javaWhat does the Connection object represent?
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.
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();
}
}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();Connect to MySQL → create the table if needed → start CRUD operations.
Why do we use CREATE TABLE IF NOT EXISTS?
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"
);executeUpdate() is used for INSERT, UPDATE, and DELETE. It returns the number of affected rows.
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);next() moves to the next row. Then use methods such as getInt() and getString() to read columns.
Which method should we use for SELECT?
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"
);WHERE id = ? tells MySQL which student to update. Without a WHERE condition, an UPDATE can change every row.
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);Just like UPDATE, DELETE should normally have a WHERE condition. DELETE FROM students would remove every student.
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().
createStudent(), readStudents(), updateStudent(), and deleteStudent(). The CLI only decides which function to call.CLI menu
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
Connects to MySQL, calls createTable(), then shows the CLI menu.
Creates the students table if it does not already exist.
Handles INSERT.
Handles SELECT and ResultSet.
Handles UPDATE.
Handles DELETE.
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:javaTest the full CRUD flow
- Choose
1and add a student. - Choose
2and verify the student appears. - Choose
3and update the same student. - Choose
2again and verify the changes. - Choose
4and delete the student. - Choose
2once more and confirm the student is gone. - Choose
5to exit.
What does main() do in this program?
Remember These JDBC Basics
For a beginner CRUD application, these are the important ideas to remember.
| Task | SQL | JDBC method |
|---|---|---|
| Create | INSERT | executeUpdate() |
| Read | SELECT | executeQuery() → ResultSet |
| Update | UPDATE | executeUpdate() |
| Delete | DELETE | executeUpdate() |
next() to move through those rows.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.