Java MySQL – DELETE Row(s)

This tutorial explains how to delete rows in a MySQL table using Java. We will go through different scenarios, including deleting a single row, deleting multiple rows based on a condition, and deleting all rows in a table. Each example includes detailed steps and Java code snippets.

Prerequisites

  • MySQL installed and running
  • Java Development Kit (JDK) installed
  • MySQL Connector/J (JDBC Driver) downloaded
  • MySQL Workbench to verify the row deletions

Step 1: Set Up MySQL Database and Table

Before running the Java code, create a sample table in MySQL. We’ll use a table named students with columns for ID, name, age, and class. Run the following SQL commands in MySQL Workbench:

</>
Copy
CREATE DATABASE IF NOT EXISTS school;
USE school;

CREATE TABLE IF NOT EXISTS students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    age INT,
    class VARCHAR(10)
);

-- Insert sample data
INSERT INTO students (name, age, class) VALUES ('Alice', 19, '10A');
INSERT INTO students (name, age, class) VALUES ('Bob', 20, '10B');
INSERT INTO students (name, age, class) VALUES ('Charlie', 21, '10A');
INSERT INTO students (name, age, class) VALUES ('Daisy', 22, '10B');

This setup creates the school database and a students table with sample data to use in our examples.

Java MySQL - DELETE Row(s) - Sample Table Data

Step 2: Set Up MySQL Connection in Java

To connect to MySQL from Java, you need the MySQL Connector/J library. Add this library to your Java project to establish the connection.

1. Download MySQL Connector/J

Go to the official MySQL Connector/J download page, download the connector, and add the JAR file to your Java project’s classpath.

Download MySQL Connector/J
Download MySQL Connector/J Zip Download

Click on the Download button.

Download MySQL Connector/J - Start Download

You may click No thanks, just start my download.
In the downloaded package, there should be a jar file.

MySQL Connector/J Jar File

2. Add the Connector to Your Java Project

For the sake of convenience, let us copy the jar file to libs folder in the Java Project.

Add the MySQL Connector to Your Java Project

Right-click on your Java project and go to Properties.

Select Java Build Path > Libraries.

Add MySQL Connector/J JAR file to Java Build Path

Add the MySQL Connector/J JAR file you downloaded.

Add MySQL Connector/J JAR file to Java Build Path - JAR Selection

Click OK.

Add MySQL Connector/J JAR file to Java Build Path - Apply and Close

Click Apply and Close.

Step 3: Java Code to DELETE Rows

We will now explore different examples for deleting rows from the students table in MySQL.

Java MySQL - DELETE Rows - Sample Table Data

Example 1: Delete a Single Row

This example demonstrates deleting a specific row based on the id of the student.

</>
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteSingleRowExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "your_password";

        try {
            // Establish a connection to MySQL
            Connection connection = DriverManager.getConnection(jdbcUrl, user, password);

            // SQL command to delete a single row
            String sql = "DELETE FROM students WHERE id = ?";

            // Prepare the statement
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);  // ID of the student to delete (e.g., Alice with id 1)

            // Execute the delete command
            int rowsDeleted = preparedStatement.executeUpdate();

            // Output the result
            if (rowsDeleted > 0) {
                System.out.println("A row was deleted successfully.");
            }

            // Close resources
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code deletes the row for the student with id = 1 (e.g., Alice).

Java MySQL - Delete Single Row - Java Program Run in Eclipse

After running the Java program, open MySQL Workbench and run the following query to verify the deletions:

</>
Copy
SELECT * FROM students;
Java MySQL - Delete Single Row - Check output in MySQL Workbench

Example 2: Delete Multiple Rows Based on a Condition

In this example, we’ll delete all rows where the class is 10A.

</>
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteConditionalRowsExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "your_password";

        try {
            // Establish a connection to MySQL
            Connection connection = DriverManager.getConnection(jdbcUrl, user, password);

            // SQL command to delete multiple rows
            String sql = "DELETE FROM students WHERE class = ?";

            // Prepare the statement
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "10A");  // Class condition

            // Execute the delete command
            int rowsDeleted = preparedStatement.executeUpdate();

            // Output the result
            System.out.println(rowsDeleted + " rows were deleted successfully.");

            // Close resources
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code deletes all rows for students in class 10A.

Java MySQL - Delete Multiple Rows Based on a Condition - Java Program Run in Eclipse

After running the Java program, open MySQL Workbench and run the following query to verify the deletions:

</>
Copy
SELECT * FROM students;
Java MySQL - Delete Multiple Rows Based on a Condition - MySQL Workbench

Example 3: Delete All Rows

This example demonstrates how to delete all rows from the students table. Note: This action cannot be undone, so use caution.

</>
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DeleteAllRowsExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "your_password";

        try {
            // Establish a connection to MySQL
            Connection connection = DriverManager.getConnection(jdbcUrl, user, password);

            // SQL command to delete all rows
            String sql = "DELETE FROM students";

            // Create a statement
            Statement statement = connection.createStatement();

            // Execute the delete command
            int rowsDeleted = statement.executeUpdate(sql);

            // Output the result
            System.out.println("All rows deleted. Total rows affected: " + rowsDeleted);

            // Close resources
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code deletes all rows from the students table, leaving it empty.

Java MySQL - DELETE All Row(s) - Run in eclipse

After running the Java program, open MySQL Workbench and run the following query to verify the deletions:

</>
Copy
SELECT * FROM students;
Java MySQL - DELETE All Row(s) - MySQL Workbench

Conclusion

This tutorial covered different ways to delete rows from a MySQL table using Java, including deleting a single row, deleting multiple rows based on a condition, and deleting all rows.