How to Perform a Cascading Delete Using JDBC?
Last Updated :
15 May, 2024
Improve
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:
- Define the relationships between tables using foreign keys.
- Use the ON DELETE CASCADE constraint in your database schema.
- Execute a delete statement on the parent table using JDBC.
Example:
// 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:

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