← Back to Chapters

JDBC DELETE Operation

?️ JDBC DELETE Operation

? Quick Overview

The JDBC DELETE operation is used to remove one or more records from a database table using SQL. In Advance Java, this is commonly performed using PreparedStatement or Statement.

? Key Concepts

  • DELETE removes existing rows from a table
  • WHERE clause controls which rows are deleted
  • PreparedStatement prevents SQL Injection
  • executeUpdate() returns number of affected rows

? Syntax / Theory

Basic SQL DELETE syntax:

? View Code Example
// SQL syntax to delete a record based on condition
DELETE FROM table_name WHERE condition;

? Code Example(s)

? View Code Example
// JDBC program to delete a student record using PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteStudent {
public static void main(String[] args) throws Exception {

// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish database connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college",
"root",
"password"
);

// SQL delete query with placeholder
String sql = "DELETE FROM students WHERE id = ?";

PreparedStatement ps = con.prepareStatement(sql);

// Set student ID to delete
ps.setInt(1, 101);

// Execute delete operation
int rows = ps.executeUpdate();

System.out.println(rows + " record deleted");

// Close connection
con.close();
}
}

? Live Output / Explanation

Output

If the student with ID 101 exists, the program will delete it and print:

1 record deleted

If no record matches, the output will be:

0 record deleted

? Interactive Simulator

Visualize how the delete command works on a database table. Enter an ID from the table on the right.

// Java Code Simulation
String sql = "DELETE FROM students WHERE id = ?";
ps.setInt(1, );
> Ready...
DATABASE: college.students
ID Name Major
101 John Doe CS
102 Jane Smith IT
103 Sam Wilson Mech
104 Lisa Ray Civil

✅ Tips & Best Practices

  • Always use WHERE clause to avoid deleting all records
  • Prefer PreparedStatement over Statement
  • Check affected row count after deletion
  • Close database resources properly

? Try It Yourself

  • Delete a record using student name instead of ID
  • Delete multiple records using a condition
  • Display a message when no record is found