In this tutorials, we are going to understand the JDBC delete program example. To do the delete data from database in JDBC, the API has given us two different methods executeUpdate(String qry) and execute(String qry).

By using the any one of those two, we can do the jdbc delete program in java. Here is the difference between the Jdbc executeUpdate() and execute().

execueteUpdate() Example :

executepdate() method returns the integer value. The value represents that the number of rows effected in the database.

int rowsEffected = stmt.executepUpdate("delete command");

execuete() Example :

execute() method returns boolean value. As we already discussed in the JDBC select example, we can use the execute() method for both select and non-select (insert, update, delete) operations. If the resultant object contains ResultSet then the execute() method returns the true, it returns false if it is an update count or no records found.

boolean isResultSet = stmt.executep("update command");

JDBC Delete Program Example :

Here is the complete example for JDBC Delete.

Jdbc_DeleteOperation_example.java
package com.onlinetutorialspoint.jdbc; 
 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Statement; 
import java.util.Scanner; 
 
public class Jdbc_DeleteOperation_Example { 
 
    public static void main(String[] args) throws Exception { 
 
        Scanner scanner = new Scanner(System.in); 
        System.out.println("Enter Student Number to delete the record"); 
 
        int studentNo = scanner.nextInt(); 
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "systemuser23!"); 
        con.setAutoCommit(false); 
        Statement stmt = con.createStatement(); 
        String query = "delete from student where sid='" + studentNo + "'"; 
        int result = stmt.executeUpdate(query); 
        con.commit(); 
        if (result == 0) { 
            System.out.println("record not found to delete"); 
        } else { 
            System.out.println(result+" no.of record(s) found and deleted"); 
        } 
        stmt.close(); 
        con.close(); 
 
    } 
 
}

Output :

Terminal
Enter Student Number to delete the record
2002
1  record(s) found and deleted

Happy Learning 🙂