JDBC - Delete record example

Posted on February 12, 2017


Technologies used:   JDK 1.8.0_121 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this section, we will show you how to delete the database records using the JDBC API. There are four steps to delete a record from a table using JDBC API.

  • Open connection to the database.
  • Create a statement object to perform a delete query.
  • Execute the executeUpdate()  method of statement object to submit a SQL query to database.
  • Close connection to the database.

JDBC Statement + Delete records example

Here is an example of using the Statement object to delete the database records.

DeleteRecordExample1.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class DeleteRecordExample1 {

  public static void main(String[] args) {
    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";
    String sql = "delete from employee where emp_id=1";

    try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password); 
        Statement stmt = conn.createStatement();) {
      
      stmt.executeUpdate(sql);
      System.out.println("Record deleted successfully");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

Record deleted successfully

JDBC PreparedStatement + Delete records example

Here is an example of using the PreparedStatement object to delete the database records.

DeleteRecordExample2.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class DeleteRecordExample2 {

  public static void main(String[] args) {
    String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
    String username = "root";
    String password = "admin";
    String sql = "delete from employee where emp_id=?";

    try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password); 
        PreparedStatement stmt = conn.prepareStatement(sql)) {
      
      stmt.setInt(1, 2);
      stmt.executeUpdate();
      
      System.out.println("Record deleted successfully");
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

Record deleted successfully