Thursday, 3 April 2025

Write a JDBC program to accept employee no from the user and update an employee record in employee table and display all record


import java.sql.*;

import java.util.Scanner;

 

class UpdateEmployee {

    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 Employee Number to update: ");

        int empNo = sc.nextInt();

        

                System.out.print("Enter new Employee Name: ");

        String empName = sc.next();

        System.out.print("Enter new Employee Salary: ");

        double empSalary = sc.nextDouble();

        

                pstmt = con.prepareStatement("UPDATE employee SET name = ?, salary = ? WHERE empno = ?");

        pstmt.setString(1, empName);

        pstmt.setDouble(2, empSalary);

        pstmt.setInt(3, empNo);

        

               int n = pstmt.executeUpdate();

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

        

                stmt = con.createStatement();

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

        

        System.out.println("\nUpdated Employee Records:");

        while (rs.next()) {

            System.out.println("Emp No: " + rs.getInt("empno") + ", Name: " + rs.getString("name") + ", Salary: " + rs.getDouble("salary"));

        }

        

              rs.close();

        stmt.close();

        pstmt.close();

        con.close();

        sc.close();

    }

}