JDBC Statement Delete record example

JDBC Statement Delete record example

Create table

CREATE TABLE `technicalkeeda`.`trn_employee` (
 `emp_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
 `first_name` VARCHAR(45) NOT NULL,
 `last_name` VARCHAR(45) NOT NULL,
 `dept` VARCHAR(60) NOT NULL,
 PRIMARY KEY (`emp_id`)
);

Jdbc Statement delete record example

package com.technicalkeeda.jdbc;

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

public class JdbcDeleteExample {

    public static void main(String[] args) {

        JdbcDeleteExample example = new JdbcDeleteExample();
        example.delete();
    }

    public void delete() {

        Statement statement = null;
        Connection connection = null;
        try {

            connection = getConnection();
            statement = connection.createStatement();

            int affectedRecords = statement.executeUpdate("DELETE FROM trn_employee WHERE emp_id = 1");
            System.out.println("Number of Records Deleted:- " + affectedRecords);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }

    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/technicalkeeda", "root", "");

        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return connection;
    }
}

Output

Number of Records Deleted:- 1