Thursday, 3 April 2025

Write a JDBC program to accept rollno from the user and delete a record from student table and display all record after deleting.

  

import java.sql.*;

import java.util.Scanner;

 

class DeleteStudent {

    public static void main(String args[]) throws Exception {

               PreparedStatement pstmt;

        Statement stmt;

        Scanner sc = new Scanner(System.in);

        

        

        Class.forName("com.mysql.jdbc.Driver");

        

  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mca", "root", "");

        

        

        System.out.print("Enter Roll Number to delete: ");

        int rollno = sc.nextInt();

        

       

        pstmt = con.prepareStatement("DELETE FROM student WHERE rollno = ?");

        pstmt.setInt(1, rollno);

        

        

        int n = pstmt.executeUpdate();

        System.out.println(n + " record(s) deleted..");

        

        

        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT * FROM student");

        

        System.out.println("\nRemaining Records:");

        while (rs.next()) {

            System.out.println("Roll No: " + rs.getInt("rollno") + ", 

                            Name: " + rs.getString("sname") + ", 

                           Age: " + rs.getInt("age"));

        }

        

        

        rs.close();

        stmt.close();

        pstmt.close();

        con.close();

        sc.close();

    }

}