To delete rows from a database using JDBC, you use the executeUpdate() method. This method is used for SQL statements that modify data (like DELETE, INSERT, or UPDATE) and returns an integer representing the number of rows affected.
While you can use a simple Statement, it is highly recommended to use a PreparedStatement to prevent SQL injection and handle parameters safely.
Example: Deleting a Row with PreparedStatement
Here is a typical implementation using the try-with-resources pattern to ensure database connections are closed properly:
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteRowExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "username";
String password = "password";
// SQL query with a placeholder (?) for the ID
String sql = "DELETE FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// Set the value for the placeholder
int idToDelete = 101;
pstmt.setInt(1, idToDelete);
// Execute the delete operation
int rowsDeleted = pstmt.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("Successfuly deleted " + rowsDeleted + " row(s).");
} else {
System.out.println("No record found with the specified ID.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Key Steps:
- Prepare the SQL: Use the
DELETEsyntax. Use?as placeholders for dynamic values. - Create a
PreparedStatement: Callconnection.prepareStatement(sql). - Bind Parameters: Use setter methods like
setInt(),setString(), orsetLong()to provide values for the placeholders (indices start at1). - Execute Update: Call
executeUpdate(). It returns the count of deleted rows. - Handle Exceptions: Wrap the code in a
try-catchblock to handleSQLException.
Which method should I use?
executeUpdate(): Use this forDELETEstatements. It returns the number of rows removed.Statement: Use only for static SQL with no user input.PreparedStatement: Always preferred for security and performance when using variables in yourWHEREclause.
