Thursday, 3 April 2025

Write JDBC application to display department wise list of employees. Accept dno, dname from user assume suitable data.


import java.sql.*;   

import java.util.Scanner; 

 

class DepartmentWiseEmployeeList {

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

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

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

       

        Scanner sc = new Scanner(System.in);

        

        System.out.print("Enter Department Number (dno): ");

        int dno = sc.nextInt();

        sc.nextLine(); 

        System.out.print("Enter Department Name (dname): ");

        String dname = sc.nextLine(); 

        

        String sql = "SELECT eno, ename FROM Employee WHERE dno = ?";

          PreparedStatement pstmt = con.prepareStatement(sql);

        pstmt.setInt(1, dno); 

       

        ResultSet rs = pstmt.executeQuery();

         

        System.out.println("\nEmployees in Department " + dname + " (" + dno + "):");

        boolean hasEmployees = false; // To check if department has employees

 

        while (rs.next()) {

            hasEmployees = true;

            int eno = rs.getInt("eno"); 

            String ename = rs.getString("ename"); 

            System.out.println("Employee ID: " + eno + ", Name: " + ename);

        }

 

        // If no employees found

        if (!hasEmployees) {

            System.out.println("No employees found in this department.");

        }

 

           rs.close();

        pstmt.close();

        con.close();

        sc.close();

    }

}