CRUD Operations in Java

Introduction

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations performed on data in almost every database-driven application. Whether you are building an employee management system, an online shopping website, a banking application, or a student management system, CRUD operations are essential for managing data efficiently.

In Java, CRUD operations are typically performed using JDBC (Java Database Connectivity), which provides a standard API for connecting Java applications to relational databases such as MySQL, Oracle, PostgreSQL, and SQL Server.

What are CRUD Operations?

CRUD Operations are the four fundamental database operations used to manage data in a table.

Operation SQL Command Purpose
Create INSERT Adds new records
Read SELECT Retrieves existing records
Update UPDATE Modifies existing records
Delete DELETE Removes records

These operations are supported by almost every relational database.

Prerequisites

Before performing CRUD operations in Java, make sure you have:

  • Java Development Kit (JDK)
  • MySQL Server
  • MySQL Connector/J (JDBC Driver)
  • Any Java IDE (IntelliJ IDEA, Eclipse, NetBeans, or VS Code)
  • Basic knowledge of SQL and JDBC

CREATE DATABASE company;

Select the database.


USE company;

Create an Employee table.


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

JDBC Connection

The following code establishes a connection with the MySQL database.


import java.sql.*;
String url = "jdbc:mysql://localhost:3306/company";
String username = "root";
String password = "password";
Connection con = DriverManager.getConnection(
        url,
        username,
        password
);

Once the connection is established, you can perform CRUD operations.

Create Operation (INSERT)

The Create operation inserts new records into the database.

Example


import java.sql.*;
public class InsertEmployee 
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                    "password");
            String sql =
                    "INSERT INTO employee(id,name,department,salary) VALUES(?,?,?,?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1,101);
            ps.setString(2,"Rahul");
            ps.setString(3,"IT");
            ps.setDouble(4,55000);
            int rows = ps.executeUpdate();
            System.out.println(rows + " Record Inserted.");
            ps.close();
            con.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

Output

1 Record Inserted.

Read Operation (SELECT)

The Read operation retrieves records from the database.

Example


import java.sql.*;
public class SelectEmployee {
    public static void main(String[] args) 
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                    "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(Exception e){
            e.printStackTrace();
        }
    }
}

Output

101 Rahul IT 55000.0

Update Operation (UPDATE)

The Update operation modifies existing records.

Example


import java.sql.*;
public class UpdateEmployee {
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                    "password");
            String sql =
                    "UPDATE employee SET salary=? WHERE id=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setDouble(1,60000);
            ps.setInt(2,101);
            int rows = ps.executeUpdate()
            System.out.println(rows + " Record Updated.");
           ps.close();
            con.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

Output

1 Record Updated.

Delete Operation (DELETE)

The Delete operation removes records from the database.

Example


import java.sql.*;
public class DeleteEmployee {
    public tatic void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/company",
                    "root",
                   "password");
            String sql =
                    "DELETE FROM employee WHERE id=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1,101);
            i rows = ps.executeUpdate();
            System.out.println(rows + " Record Deleted.");
            ps.close();
            con.close()
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

Output

1 Record Deleted.

Complete CRUD Workflow


   Java Application
        │
        ▼
     JDBC Driver
        │
        ▼
 MySQL Database
        │
        ├── INSERT (Create)
        ├── SELECT (Read)
        ├── UPDATE (Update)
        └── DELETE (Delete)

Why Use PreparedStatement?

In all CRUD examples, we use PreparedStatement instead of Statement because it offers several advantages:

  • Prevents SQL injection attacks.
  • Improves performance by precompiling SQL statements.
  • Supports parameterized queries.
  • Makes code easier to read and maintain.
  • Handles special characters safely.

Example:


String sql = "SELECT * FROM employee WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);

Real-life Example

Imagine you are developing a Student Management System.

The application performs CRUD operations as follows:

  • Create: Add a new student during admission.
  • Read: Display student information on the dashboard.
  • Update: Modify the student’s contact details or marks.
  • Delete: Remove the student’s record after graduation or transfer.

Similarly, CRUD operations are used in:

  • Banking Applications
  • Hospital Management Systems
  • Online Shopping Websites
  • Library Management Systems
  • Hotel Booking Systems
  • Payroll Management Systems
  • Inventory Management Systems

Advantages of CRUD Operations

  • Simple and easy to understand.
  • Forms the foundation of database applications.
  • Supports efficient data management.
  • Works with all relational databases.
  • Enables secure data manipulation using JDBC.
  • Easy to integrate with Java frameworks like Spring Boot and Hibernate.
  • Suitable for small and enterprise-level applications.

Best Practices

Follow these best practices while implementing CRUD operations:

📖
Best Practices:
  • Always use PreparedStatement instead of Statement.
  • Close Connection, PreparedStatement, and ResultSet after use.
  • Use try-with-resources for automatic resource management.
  • Validate user input before executing SQL statements.
  • Store database credentials securely in configuration files or environment variables.
  • Use transactions when multiple operations must succeed or fail together.
  • Handle SQLException properly and log errors.
  • Implement connection pooling for better performance in large applications.
  • Always use PreparedStatement instead of Statement.
  • Close Connection, PreparedStatement, and ResultSet after use.
  • Use try-with-resources for automatic resource management.
  • Validate user input before executing SQL statements.
  • Store database credentials securely in configuration files or environment variables.
  • Use transactions when multiple operations must succeed or fail together.
  • Handle SQLException properly and log errors.
  • Implement connection pooling for better performance in large applications.

Common Mistakes

Beginners often make these mistakes:

  • Forgetting to close database connections.
  • Using Statement with user input.
  • Writing incorrect SQL queries.
  • Ignoring SQL exceptions.
  • Hardcoding database credentials.
  • Not checking the number of affected rows.
  • Using the wrong database URL or port number.
  • Forgetting to commit transactions when auto-commit is disabled.

Conclusion

CRUD operations are the backbone of every database-driven Java application. Using JDBC, developers can easily create, read, update, and delete records in relational databases such as MySQL. By understanding these operations and following best practices—such as using PreparedStatement, validating user input, handling exceptions properly, and closing resources—you can build secure, efficient, and scalable applications.

Related Java Tutorials