Delete Records

Delete Records

In this tutorial, we are going to discuss about how to delete records from table using JDBC. Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

Here’s a simple example of delete records using JDBC (Java Database Connectivity). In this example, I’ll demonstrate how to connect to a MySQL database and delete records into the table named “employees” with three columns: “id”, “name”, and “salary”.

Delete Records

Deleting records from a table using JDBC follows a similar pattern to inserting and updating records. Here’s a basic example demonstrating how to delete records using JDBC:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeleteExample {

    public static void main(String[] args) {
        // JDBC URL, username, and password for your database
        String url = "jdbc:mysql://localhost:3306/employee";
        String user = "ashok";
        String password = "Ashok@123";

        // SQL DELETE statement
        String deleteSQL = "DELETE FROM employee WHERE id = ?";

        try (
            // Establishing connection to the database
            Connection connection = DriverManager.getConnection(url, user, password);
            // Creating a prepared statement
            PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL)
        ) {
            // Setting value for the placeholder (?)
            preparedStatement.setInt(1, 87); // Assuming 'id' is the primary key column

            // Executing the DELETE statement
            int rowsAffected = preparedStatement.executeUpdate();

            System.out.println(rowsAffected + " row(s) deleted successfully.");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Replace "employee", "ashok", "Ashok@143", "employee", "name", "salary", and "id" with your actual database name, username, password, table name, column names, and the primary key column name, respectively.

Ensure that:

  • You have the appropriate permissions to delete records from the table in the database.
  • Handle exceptions properly, especially when dealing with database operations. In this example, exceptions are simply printed, but in a real application, you would handle them more robustly, possibly logging them or presenting meaningful error messages to the user.
  • Use PreparedStatement to safely delete records and prevent SQL injection attacks.

That’s all about the how to delete records from table using JDBC. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Delete Records
Scroll to top