Slip No 20 Q A

Write a JDBC program to delete the details of given employee (ENo EName Salary). Accept employee ID through command line.

import java.sql.*;

public class DeleteEmployee {

    public static void main(String[] args) {

        // Check if employee ID is provided
        if(args.length != 1) {
            System.out.println("Usage: java DeleteEmployee <EmployeeID>");
            return;
        }

        int empId = Integer.parseInt(args[0]);

        String url = "jdbc:mysql://localhost:3306/testdb"; // Change DB name
        String user = "root"; // DB username
        String password = "root"; // DB password

        try {
            // Load JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish Connection
            Connection con = DriverManager.getConnection(url, user, password);

            // Prepare DELETE statement
            String deleteQuery = "DELETE FROM Emp WHERE ENo = ?";
            PreparedStatement ps = con.prepareStatement(deleteQuery);
            ps.setInt(1, empId);

            // Execute update
            int rows = ps.executeUpdate();

            if(rows > 0) {
                System.out.println("Employee with ID " + empId + " deleted successfully.");
            } else {
                System.out.println("Employee with ID " + empId + " not found.");
            }

            // Close resources
            ps.close();
            con.close();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Run (example: delete employee with ID 101):

Command : java DeleteEmployee 101

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top