Open In App

How to Perform a Cascading Delete Using JDBC?

Last Updated : 15 May, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In JDBC, the Cascading Delete Operation is a technique of databases that are used to delete the record parent table. In this article, we will learn How to perform a cascading delete using JDBC.

Cascading Delete Using JDBC

To Perform a Cascading Delete using JDBC (Java Database Connectivity), you need to follow these General Steps:

  1. Define the relationships between tables using foreign keys.
  2. Use the ON DELETE CASCADE constraint in your database schema.
  3. Execute a delete statement on the parent table using JDBC.

Example:

Java
// Java Program to Perform a Cascading
// Delete using JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

// Driver Class
public class CascadeOperation {
    // Main Function
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // Database connection
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/employee_management_system",
                "root", "admin");
            conn.setAutoCommit(false);

            stmt = conn.createStatement();

            // Execute the DELETE statement
            stmt.executeUpdate(
                "DELETE FROM employee WHERE id = 1");

            // Save the transaction
            conn.commit();
            System.out.println(
                "Cascading delete completed successfully.");
        } catch (SQLException e) {

            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            e.printStackTrace();
        } finally {

            try {
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException closeEx) {
                closeEx.printStackTrace();
            }
        }
    }
}

Output:

Output of the Program

Explaination of the above Program:

  1. In the above code, we establish a connection to a MySQL database named that is employee_management_system using JDBC.
  2. executeUpdate() executes the DELETE operation where the condition is deletes the employee record with an id of 1 from the employee table.
  3. If the DELETE statement is executed successfully, the code commits the transaction using the commit() method and makes the changes permanent.

Next Article
Article Tags :
Practice Tags :

Similar Reads