Popular Searches
Popular Course Categories
Popular Courses

Performing Database CRUD Operations Using JDBC

Performing Database CRUD Operations Using JDBC

Advanced JDBC Operations and Transactions

Performing Database CRUD Operations Using JDBC

Course: Advanced Java Training

Topic: Performing Database CRUD Operations Using JDBC

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to CRUD Operations in JDBC

CRUD stands for Create, Read, Update, and Delete. These four operations are the foundation of most database-driven applications. They allow an application to insert new records, retrieve existing records, modify stored information, and remove records when they are no longer required.

Java Database Connectivity (JDBC) is a Java API used to communicate with relational databases such as MySQL, PostgreSQL, Oracle Database, and SQL Server. JDBC allows Java applications to execute SQL statements and process the results returned by a database.

For example, an employee management system might use CRUD operations to:

  • Create: Add a new employee to the database.
  • Read: Display employee details.
  • Update: Change an employee's department or salary.
  • Delete: Remove an employee record when authorized.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the meaning and purpose of CRUD operations.
  • Establish a database connection using JDBC.
  • Insert records using INSERT statements.
  • Retrieve records using SELECT statements and ResultSet.
  • Modify records using UPDATE statements.
  • Delete records using DELETE statements.
  • Use PreparedStatement to handle SQL parameters safely.
  • Handle SQL exceptions and close database resources correctly.
  • Apply transactions and validation to improve data integrity.

3. JDBC Components Used in CRUD Operations

Component Purpose
DriverManager Obtains a database connection using a JDBC URL and connection details.
Connection Represents a database session and provides transaction management methods.
PreparedStatement Executes parameterized SQL statements with values supplied through setter methods.
Statement Executes SQL statements without parameter placeholders; use with care when SQL includes external input.
ResultSet Provides access to rows returned by a query.
SQLException Represents errors encountered while accessing or processing database operations.

4. Understanding the CRUD Workflow

Java Application
       |
       v
Establish JDBC Connection
       |
       v
Create PreparedStatement
       |
       v
Execute SQL Operation
       |
       +---- INSERT  --> Create a record
       |
       +---- SELECT  --> Read records
       |
       +---- UPDATE  --> Modify a record
       |
       +---- DELETE  --> Remove a record
       |
       v
Process Results or Update Counts
       |
       v
Close JDBC Resources

CRUD operations commonly use executeUpdate() for INSERT, UPDATE, and DELETE statements, and executeQuery() for SELECT statements that return a ResultSet.

5. Setting Up the Database

For the examples in these notes, we will use MySQL and an employee table. You can run the following SQL commands in MySQL Workbench or another compatible SQL client.

5.1 Create a Database

CREATE DATABASE company_db;

USE company_db;

5.2 Create an Employees Table

CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    department VARCHAR(100),
    salary DECIMAL(10, 2) NOT NULL
);

5.3 Insert Sample Records

INSERT INTO employees (name, email, department, salary)
VALUES
('Amit Sharma', '[email protected]', 'IT', 45000.00),
('Neha Patil', '[email protected]', 'HR', 42000.00),
('Rahul Verma', '[email protected]', 'Finance', 50000.00);

The id column is automatically generated. When inserting a new employee, the application can omit the ID and let MySQL assign it.

6. Configuring the JDBC Driver

Make sure the appropriate JDBC driver is available to your project. For MySQL, the driver is MySQL Connector/J. A Maven-based project can include the driver as a dependency; use a version compatible with your Java and MySQL environment.

Example Maven dependency structure:

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

Replace YOUR_COMPATIBLE_VERSION with a real Connector/J version from the official MySQL documentation or your project's approved dependency configuration. Do not leave the placeholder in a build file.

7. Creating a Reusable Database Connection Utility

Instead of repeating connection details in every CRUD method, create a helper class that centralizes connection creation. This example reads credentials from environment variables to avoid hard-coding passwords.

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

public final class DBConnection {
    private static final String URL =
        "jdbc:mysql://localhost:3306/company_db";

    private DBConnection() {
        // Prevent utility class instantiation.
    }

    public static Connection getConnection()
            throws SQLException {
        String user = System.getenv("DB_USER");
        String password = System.getenv("DB_PASSWORD");

        if (user == null || password == null) {
            throw new SQLException(
                "Set DB_USER and DB_PASSWORD environment variables."
            );
        }

        return DriverManager.getConnection(URL, user, password);
    }
}

7.1 How It Works

  • The JDBC URL identifies the database server and database name.
  • The environment variables provide the database username and password.
  • DriverManager.getConnection() requests a connection from the configured JDBC driver.
  • The calling method is responsible for closing the returned connection.

Configure DB_USER and DB_PASSWORD with valid credentials before running the examples. In production systems, use an approved secrets manager or secure application configuration.

8. CREATE Operation: Inserting Records

The Create operation inserts a new record into a database table. In SQL, the INSERT statement is used to add data.

8.1 Basic INSERT Syntax

INSERT INTO table_name (column1, column2, column3)
VALUES (?, ?, ?);

The question marks are parameter placeholders. When using PreparedStatement, supply each value with a suitable setter method.

8.2 Java Example: Insert an Employee

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class EmployeeCreate {
    public static int addEmployee(
            String name,
            String email,
            String department,
            BigDecimal salary) throws SQLException {

        String sql =
            "INSERT INTO employees " +
            "(name, email, department, salary) " +
            "VALUES (?, ?, ?, ?)";

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

            statement.setString(1, name);
            statement.setString(2, email);
            statement.setString(3, department);
            statement.setBigDecimal(4, salary);

            return statement.executeUpdate();
        }
    }

    public static void main(String[] args) {
        try {
            int rows = addEmployee(
                "Priya Desai",
                "[email protected]",
                "Marketing",
                new BigDecimal("48000.00")
            );

            System.out.println(
                rows + " employee record inserted."
            );
        } catch (SQLException e) {
            System.err.println("Unable to insert employee.");
            e.printStackTrace();
        }
    }
}

8.3 Explanation

  1. The SQL statement specifies the table, columns, and parameter placeholders.
  2. DBConnection.getConnection() establishes a database connection.
  3. prepareStatement() creates a PreparedStatement for the SQL.
  4. Setter methods provide values for each placeholder.
  5. executeUpdate() executes the INSERT operation and returns the affected-row count.
  6. Try-with-resources closes the statement and connection automatically.

8.4 Inserting a Record and Retrieving Its Generated ID

When the table uses an auto-increment primary key, you can request the generated key from JDBC.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertWithGeneratedKey {
    public static void main(String[] args) {
        String sql =
            "INSERT INTO employees " +
            "(name, email, department, salary) " +
            "VALUES (?, ?, ?, ?)";

        try (Connection connection = DBConnection.getConnection();
             PreparedStatement statement =
                 connection.prepareStatement(
                     sql, Statement.RETURN_GENERATED_KEYS
                 )) {

            statement.setString(1, "Karan Mehta");
            statement.setString(2, "[email protected]");
            statement.setString(3, "Operations");
            statement.setBigDecimal(
                4, new java.math.BigDecimal("46000.00")
            );

            int rows = statement.executeUpdate();

            if (rows > 0) {
                try (ResultSet keys = statement.getGeneratedKeys()) {
                    if (keys.next()) {
                        System.out.println(
                            "New employee ID: " + keys.getLong(1)
                        );
                    }
                }
            }

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

Generated-key support depends on the database and JDBC driver. Use the driver documentation if the application requires database-specific behavior.

9. READ Operation: Retrieving Records

The Read operation retrieves stored information. SQL SELECT statements can return one record, selected columns, or multiple rows based on a condition.

9.1 Basic SELECT Syntax

SELECT column1, column2
FROM table_name
WHERE condition;

9.2 Java Example: Display All Employees

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EmployeeRead {
    public static void displayEmployees() throws SQLException {
        String sql =
            "SELECT id, name, email, department, salary " +
            "FROM employees ORDER BY id";

        try (Connection connection = DBConnection.getConnection();
             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");
                String department =
                    resultSet.getString("department");
                BigDecimal salary =
                    resultSet.getBigDecimal("salary");

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

    public static void main(String[] args) {
        try {
            displayEmployees();
        } catch (SQLException e) {
            System.err.println("Unable to read employees.");
            e.printStackTrace();
        }
    }
}

Important: Add the following import to the code above because it uses BigDecimal:

import java.math.BigDecimal;

9.3 Understanding ResultSet

A ResultSet represents the rows returned by a query. Its cursor initially points before the first row. Calling next() moves the cursor to the next row and returns true when a row is available.

Method Purpose
next() Moves to the next row.
getInt("id") Reads an integer column.
getString("name") Reads a text column.
getBigDecimal("salary") Reads a decimal value with suitable precision.
getDate("join_date") Reads a SQL date column.

Use column labels or valid column indexes. When reading nullable columns, remember that SQL NULL values require appropriate handling; primitive getters may return default values, so use wasNull() when needed.

9.4 Reading One Employee by ID

public static void findEmployeeById(int employeeId)
        throws SQLException {

    String sql =
        "SELECT id, name, email, department, salary " +
        "FROM employees WHERE id = ?";

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

        statement.setInt(1, employeeId);

        try (ResultSet resultSet = statement.executeQuery()) {
            if (resultSet.next()) {
                System.out.println(
                    "Employee: " +
                    resultSet.getString("name")
                );
                System.out.println(
                    "Email: " +
                    resultSet.getString("email")
                );
            } else {
                System.out.println("Employee not found.");
            }
        }
    }
}

Place this method inside a class that imports Connection, PreparedStatement, ResultSet, and SQLException. It can be called with an employee ID to find a single record.

10. UPDATE Operation: Modifying Records

The Update operation changes existing records. SQL UPDATE statements should normally include a WHERE clause to identify the intended row or rows.

10.1 Basic UPDATE Syntax

UPDATE table_name
SET column1 = ?, column2 = ?
WHERE id = ?;

10.2 Java Example: Update an Employee's Department and Salary

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class EmployeeUpdate {
    public static int updateEmployee(
            int employeeId,
            String department,
            BigDecimal salary) throws SQLException {

        String sql =
            "UPDATE employees " +
            "SET department = ?, salary = ? " +
            "WHERE id = ?";

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

            statement.setString(1, department);
            statement.setBigDecimal(2, salary);
            statement.setInt(3, employeeId);

            return statement.executeUpdate();
        }
    }

    public static void main(String[] args) {
        try {
            int rows = updateEmployee(
                1,
                "Product Development",
                new BigDecimal("55000.00")
            );

            if (rows == 0) {
                System.out.println(
                    "No matching employee was updated."
                );
            } else {
                System.out.println(
                    rows + " employee record updated."
                );
            }
        } catch (SQLException e) {
            System.err.println("Unable to update employee.");
            e.printStackTrace();
        }
    }
}

10.3 Why the WHERE Clause Matters

The WHERE clause restricts which records are updated. Without it, the database may update every row in the table.

-- Updates only the employee with ID 2
UPDATE employees
SET department = 'Finance'
WHERE id = 2;

-- Dangerous: updates every employee's department
UPDATE employees
SET department = 'Finance';

Before running an update in a production system, validate the target record and ensure that the database account has only the necessary permissions.

11. DELETE Operation: Removing Records

The Delete operation removes records from a table. A DELETE statement can target one or more rows using a WHERE clause.

11.1 Basic DELETE Syntax

DELETE FROM table_name
WHERE id = ?;

11.2 Java Example: Delete an Employee by ID

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class EmployeeDelete {
    public static int deleteEmployee(int employeeId)
            throws SQLException {

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

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

            statement.setInt(1, employeeId);
            return statement.executeUpdate();
        }
    }

    public static void main(String[] args) {
        try {
            int rows = deleteEmployee(3);

            if (rows > 0) {
                System.out.println("Employee deleted successfully.");
            } else {
                System.out.println("Employee not found.");
            }
        } catch (SQLException e) {
            System.err.println("Unable to delete employee.");
            e.printStackTrace();
        }
    }
}

11.3 Important Delete Precautions

  • Always verify the target records before deleting data.
  • Use a WHERE clause unless intentionally deleting all rows.
  • Consider a confirmation step for user-facing applications.
  • Understand foreign-key constraints and related records.
  • For business-critical records, consider soft deletion using a status or timestamp column.
  • Use transactions when deletion is part of a larger multi-step operation.

12. Understanding executeQuery() and executeUpdate()

Method Typical Use Return Value
executeQuery() SELECT statements that return rows A ResultSet
executeUpdate() INSERT, UPDATE, DELETE, and certain SQL statements that do not return a ResultSet An affected-row count, or zero for statements that return no row count
execute() Statements where the result type may vary A boolean indicating whether the first result is a ResultSet

Choose the method that matches the SQL statement and expected result. For normal CRUD code, SELECT uses executeQuery(), while INSERT, UPDATE, and DELETE generally use executeUpdate().

13. CRUD Operations and SQL Injection Prevention

SQL injection can occur when untrusted input is combined directly with SQL text. PreparedStatement helps prevent this problem by treating supplied parameter values as data rather than executable SQL syntax.

13.1 Unsafe Example

// Avoid concatenating user input into SQL.
String sql =
    "SELECT * FROM employees WHERE email = '" +
    userInput + "'";

If the input contains SQL syntax, concatenation can change the intended query. Never build SQL by inserting untrusted values directly into the statement text.

13.2 Safer Example

String sql =
    "SELECT id, name, email FROM employees WHERE email = ?";

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

    statement.setString(1, userInput);

    try (ResultSet resultSet = statement.executeQuery()) {
        while (resultSet.next()) {
            System.out.println(resultSet.getString("name"));
        }
    }
}

PreparedStatement parameters represent values, not SQL identifiers. If a query needs a dynamic table name or column name, validate it against a strict allowlist rather than passing it as a normal parameter.

14. Handling Exceptions in JDBC CRUD Operations

Database operations can fail because of invalid SQL, unavailable servers, invalid credentials, duplicate values, constraint violations, or network problems. Java reports many such problems through SQLException.

14.1 Useful SQLException Methods

Method Description
getMessage() Returns the error message.
getSQLState() Returns the SQL state when available.
getErrorCode() Returns a vendor-specific error code.
getNextException() Provides access to the next chained SQL exception.

14.2 Example Exception Handling

try {
    int rows = EmployeeCreate.addEmployee(
        "Sara Khan",
        "[email protected]",
        "Design",
        new java.math.BigDecimal("44000.00")
    );

    System.out.println("Rows inserted: " + rows);

} catch (SQLException e) {
    System.err.println("Database operation failed.");
    System.err.println("SQL state: " + e.getSQLState());
    System.err.println("Error code: " + e.getErrorCode());
    e.printStackTrace();
}

In production applications, use structured logging and return appropriate user-facing messages. Avoid exposing credentials, connection strings containing secrets, or sensitive database details to end users.

15. Using Transactions for Multiple CRUD Operations

Some business operations require several SQL statements to succeed together. For example, creating an order might require inserting an order record and several order-item records. A transaction helps ensure that these operations are committed as a unit.

15.1 Transaction Example

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class EmployeeTransaction {
    public static void updateEmployeeDetails(
            int employeeId,
            String department,
            java.math.BigDecimal salary) throws SQLException {

        String updateDepartment =
            "UPDATE employees SET department = ? WHERE id = ?";
        String updateSalary =
            "UPDATE employees SET salary = ? WHERE id = ?";

        try (Connection connection = DBConnection.getConnection()) {
            connection.setAutoCommit(false);

            try {
                try (PreparedStatement departmentStatement =
                         connection.prepareStatement(updateDepartment);
                     PreparedStatement salaryStatement =
                         connection.prepareStatement(updateSalary)) {

                    departmentStatement.setString(1, department);
                    departmentStatement.setInt(2, employeeId);

                    int departmentRows =
                        departmentStatement.executeUpdate();

                    salaryStatement.setBigDecimal(1, salary);
                    salaryStatement.setInt(2, employeeId);

                    int salaryRows =
                        salaryStatement.executeUpdate();

                    if (departmentRows != 1 || salaryRows != 1) {
                        throw new SQLException(
                            "Expected to update exactly one employee."
                        );
                    }
                }

                connection.commit();

            } catch (SQLException e) {
                try {
                    connection.rollback();
                } catch (SQLException rollbackError) {
                    e.addSuppressed(rollbackError);
                }
                throw e;
            }
        }
    }
}

15.2 Transaction Explanation

  1. setAutoCommit(false) disables automatic commit for the connection.
  2. The application executes both updates.
  3. The affected-row counts are checked.
  4. If both updates succeed, commit() makes the transaction permanent.
  5. If a SQL error occurs, rollback() attempts to undo uncommitted changes.

Database transaction behavior depends on the database engine and schema. For example, table storage engines and constraints can affect whether changes can be rolled back. Applications should also handle rollback errors and connection failures.

16. Input Validation and Data Integrity

Validation helps ensure that the application sends sensible values to the database. Database constraints provide an additional layer of protection.

Field Example Validation
Name Required and not blank; enforce an appropriate length limit.
Email Required, format-checked, and unique when required by the application.
Department Validate against allowed department names if the business rules require it.
Salary Use BigDecimal for decimal currency values and reject invalid or negative amounts when the business rules prohibit them.
Employee ID Validate the expected numeric range and verify that the target record exists when appropriate.

Do not rely exclusively on application-side validation. Constraints such as PRIMARY KEY, UNIQUE, NOT NULL, CHECK, and FOREIGN KEY can help maintain data integrity at the database level.

17. Common JDBC CRUD Errors and Solutions

Problem Possible Cause Solution
No suitable driver JDBC driver missing or URL is incorrect. Add the correct driver dependency and verify the URL format.
Access denied Invalid credentials or insufficient privileges. Check the database account and permissions.
Duplicate entry A UNIQUE or PRIMARY KEY constraint was violated. Validate the value or handle the conflict according to business rules.
Unknown column SQL refers to a column that does not exist or is misspelled. Verify the table schema and query column names.
Zero rows updated No row matched the WHERE condition, or the database reports no changed rows for the operation. Check the target ID and database-specific affected-row behavior.
Data truncation Value exceeds a column's capacity or has an incompatible format. Validate input and confirm the column data type and size.
Connection leak Connection, statement, or result set was not closed. Use try-with-resources for JDBC resources.
SQL injection risk Untrusted input was concatenated into SQL. Use PreparedStatement and validate dynamic identifiers.
Foreign-key constraint failure Delete or update conflicts with related records. Review relationships and apply the correct business rule.

18. Complete CRUD Project Structure

A simple employee CRUD project can be organized into separate classes to make the code easier to maintain.

EmployeeCRUDProject/
|
|-- src/
|   |-- DBConnection.java
|   |-- EmployeeCreate.java
|   |-- EmployeeRead.java
|   |-- EmployeeUpdate.java
|   |-- EmployeeDelete.java
|   |-- Employee.java
|   |-- EmployeeDAO.java
|   |-- Main.java
|
|-- pom.xml

In a larger application, a model class represents employee data, a DAO (Data Access Object) class groups database operations, and a service layer handles business rules. Keeping these responsibilities separate improves readability and testability.

19. Suggested Employee Model and DAO Design

19.1 Employee Model

import java.math.BigDecimal;

public class Employee {
    private int id;
    private String name;
    private String email;
    private String department;
    private BigDecimal salary;

    public Employee(
            int id,
            String name,
            String email,
            String department,
            BigDecimal salary) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.department = department;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public String getDepartment() {
        return department;
    }

    public BigDecimal getSalary() {
        return salary;
    }
}

19.2 DAO Responsibilities

An EmployeeDAO class can contain methods such as:

  • createEmployee(Employee employee)
  • findEmployeeById(int id)
  • findAllEmployees()
  • updateEmployee(Employee employee)
  • deleteEmployee(int id)

Each method should use parameterized SQL, manage its JDBC resources, and handle database errors in a consistent way. The examples in this topic can be adapted into the DAO methods.

20. Practical Mini Project: Employee Management System

Create a console-based employee management application that performs all four CRUD operations.

20.1 Project Requirements

  • Add an employee with name, email, department, and salary.
  • Display all employees.
  • Search for an employee by ID.
  • Update an employee's department and salary.
  • Delete an employee by ID after confirmation.
  • Handle duplicate emails and invalid values.
  • Use PreparedStatement for all user-supplied SQL values.
  • Close connections, statements, and result sets reliably.

20.2 Example Console Menu

===== Employee Management System =====
1. Add Employee
2. View All Employees
3. Search Employee by ID
4. Update Employee
5. Delete Employee
6. Exit
Enter your choice:

20.3 Suggested Development Steps

  1. Create the database and employees table.
  2. Configure the JDBC driver dependency.
  3. Implement the DBConnection utility.
  4. Create the Employee model class.
  5. Implement CRUD methods in EmployeeDAO.
  6. Build a menu-driven Main class to accept user choices.
  7. Test successful operations, missing records, invalid input, and duplicate emails.
  8. Review resource management and error handling before completing the project.

21. Best Practices for JDBC CRUD Operations

  • Use PreparedStatement for parameterized SQL queries.
  • Never concatenate untrusted input directly into SQL statements.
  • Use try-with-resources to close Connection, PreparedStatement, and ResultSet objects.
  • Keep database credentials outside source code.
  • Use a WHERE clause for targeted UPDATE and DELETE operations.
  • Validate user input before database operations.
  • Use database constraints to protect data integrity.
  • Use transactions when multiple operations must succeed or fail together.
  • Check affected-row counts where the business operation requires confirmation.
  • Use BigDecimal for precise decimal values such as salaries and currency.
  • Log technical errors securely and show meaningful messages to users.
  • Consider DataSource and connection pooling for applications with frequent database access.

22. Interview Questions and Answers

Q1. What does CRUD stand for?

Answer: CRUD stands for Create, Read, Update, and Delete. These operations represent the basic ways an application manages stored records.

Q2. Which SQL statements are used for CRUD?

Answer: INSERT creates records, SELECT reads records, UPDATE modifies records, and DELETE removes records.

Q3. What is the difference between executeQuery() and executeUpdate()?

Answer: executeQuery() returns a ResultSet and is typically used for SELECT statements. executeUpdate() returns an affected-row count for INSERT, UPDATE, DELETE, and certain other statements.

Q4. What is PreparedStatement?

Answer: PreparedStatement is a JDBC interface for executing parameterized SQL. It supports typed parameters and helps prevent SQL injection when values are bound correctly.

Q5. What is a ResultSet?

Answer: ResultSet represents the rows returned by a query and provides methods to move through those rows and retrieve column values.

Q6. Why should an UPDATE statement use a WHERE clause?

Answer: The WHERE clause restricts which rows are modified. Without it, the UPDATE statement may affect every row in the table.

Q7. Why is a WHERE clause important in DELETE?

Answer: It identifies the records that should be removed. Without a WHERE clause, a DELETE statement can remove all rows from the target table.

Q8. How do you obtain the generated ID after inserting a record?

Answer: Request generated keys when creating the PreparedStatement by using Statement.RETURN_GENERATED_KEYS, execute the insert, and retrieve the keys with getGeneratedKeys(), subject to driver support.

Q9. How do you manage multiple database changes as one operation?

Answer: Disable auto-commit, perform the operations, commit if they all succeed, and attempt rollback if an error occurs.

Q10. Why should JDBC resources be closed?

Answer: Closing resources releases database and application resources and prevents resource leaks. Try-with-resources is the recommended approach for JDBC objects that implement AutoCloseable.

23. Practice Exercises

  1. Write a Java program to insert a new employee record.
  2. Display every employee using a SELECT statement and ResultSet.
  3. Search for an employee by ID using PreparedStatement.
  4. Update an employee's salary and display the number of affected rows.
  5. Delete an employee by ID and handle the case where the ID does not exist.
  6. Retrieve and print the generated primary key after inserting an employee.
  7. Write a transaction that performs two related updates and rolls back if either operation fails.
  8. Test how the application handles a duplicate email address.
  9. Identify and correct an SQL injection vulnerability in a sample query.
  10. Refactor separate CRUD methods into an EmployeeDAO class.

24. Quick Revision Checklist

  • CRUD means Create, Read, Update, and Delete.
  • INSERT adds a record.
  • SELECT retrieves records.
  • UPDATE modifies existing records.
  • DELETE removes records.
  • PreparedStatement is recommended for queries with parameters.
  • executeQuery() returns a ResultSet for queries that return rows.
  • executeUpdate() returns an affected-row count for common data modification statements.
  • ResultSet.next() moves to the next row.
  • Try-with-resources closes JDBC resources automatically.
  • Use transactions for related changes that must succeed together.
  • Validate inputs and protect credentials.
  • Use WHERE clauses carefully in UPDATE and DELETE statements.

25. Official Documentation and Further Reading

26. Conclusion

Performing CRUD operations using JDBC is a core skill for developing Java applications that interact with relational databases. By combining DriverManager, Connection, PreparedStatement, ResultSet, and proper exception handling, developers can build applications that create, retrieve, update, and delete data safely and reliably.

Practice each operation independently before combining them into an Employee Management System. Focus on parameterized SQL, input validation, transaction handling, correct resource closure, and secure database configuration to develop good JDBC programming habits.

Explore the course: Advanced Java Training at JustAcademy

Register for a demo: Register for a Course Demo

Visit the website: JustAcademy

Previous Next
whatsapp