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.
Basic SQL DELETE syntax:
// SQL syntax to delete a record based on condition
DELETE FROM table_name WHERE condition;
// 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();
}
}
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
Visualize how the delete command works on a database table. Enter an ID from the table on the right.
| ID | Name | Major |
|---|---|---|
| 101 | John Doe | CS |
| 102 | Jane Smith | IT |
| 103 | Sam Wilson | Mech |
| 104 | Lisa Ray | Civil |