JDBC Delete Program

we are going to understand the JDBC delete Program. 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("delete command");
                    
JDBC Delete Program :

                        package com.navabitsolutions.jdbc; 
 
                        import java.sql.Connection; 
                        import java.sql.DriverManager; 
                        import java.sql.Statement; 
                        import java.util.Scanner; 
                        
                        public class JdbcDeleteOperationExample { 
                        
                            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/navabitsolutions", "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(); 
                        
                            } 
                        
                        }