Delete specified record from database - Java

Q. Write a program to delete the nth record from the database.

Answer:

The delete query used to delete the record from the database. Below example shows how to delete the nth record from oracle database. We are using Emp table.

SQL query for deleting nth record.

delete  from emp where emp_id=(select max(emp_id) from emp where rownum <=  nth

DeleteTest.java

import java.sql.*;
import java.util.Scanner;
class DeleteTest
{
     public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
     public static final String DBUSER = "local";
     public static final String DBPASS = "test";
     public static void main(String[] args) throws Exception
     {
          Scanner sc = new Scanner(System.in);
          System.out.print("Enter record number which you want to delete: ");
          int stno = sc.nextInt();

          Class.forName("oracle.jdbc.driver.OracleDriver");
          Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
          String qry = "delete  from emp where emp_id=(select max(emp_id) from emp where rownum<=?)";
          //create PreparedStatement object
          PreparedStatement pst=con.prepareStatement(qry);
          pst.setInt(1,stno);//set value to parameter
          //execute the sql query
          int count = pst.executeUpdate();

          if(count != 0)
               System.out.println(count+" Record deleted successfully\n");
          else            
               System.out.println("Record deletion failed\n");

          pst.close();
          con.close();
     }
}


Output:

delete record