0% found this document useful (0 votes)
14 views16 pages

JDBC Slips Answer

The document contains multiple Java programs that interact with a PostgreSQL database. The programs include functionalities for managing teacher and employee records, displaying database metadata, and handling product information. Each program demonstrates the use of JDBC for database operations, including creating tables, inserting records, and retrieving data.

Uploaded by

chipadeshailesh7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

JDBC Slips Answer

The document contains multiple Java programs that interact with a PostgreSQL database. The programs include functionalities for managing teacher and employee records, displaying database metadata, and handling product information. Each program demonstrates the use of JDBC for database operations, including creating tables, inserting records, and retrieving data.

Uploaded by

chipadeshailesh7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

/*

Write a Java program to accept the details of Teacher (TNo, TName, Subject).
Insert at least 5 Records into Teacher Table and display the details of Teacher who is teaching
"JAVA" Subject. (Use PreparedStatement Interface)
*/
import java.sql.*;

public class TeacherDatabase {

// Method to insert records into Teacher table


public static void insertTeachers() throws SQLException {
// PostgreSQL database connection details
String url = "jdbc:postgresql://localhost:5432/dpu"; // Replace with your DB name
String user = "postgres"; // Replace with your DB username
String password = "postgres"; // Replace with your DB password

Connection conn = DriverManager.getConnection(url, user, password);

// SQL query to insert teacher details


String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject) VALUES (?, ?, ?)";

PreparedStatement pstmt = conn.prepareStatement(insertQuery);

// Insert 5 records into Teacher table


pstmt.setInt(1, 101); pstmt.setString(2, "John Doe"); pstmt.setString(3, "JAVA");
pstmt.executeUpdate();

pstmt.setInt(1, 102); pstmt.setString(2, "Jane Smith"); pstmt.setString(3, "Python");


pstmt.executeUpdate();

pstmt.setInt(1, 103); pstmt.setString(2, "Alice Brown"); pstmt.setString(3, "JAVA");


pstmt.executeUpdate();

pstmt.setInt(1, 104); pstmt.setString(2, "Bob White"); pstmt.setString(3, "C++");


pstmt.executeUpdate();

pstmt.setInt(1, 105); pstmt.setString(2, "Charlie Green"); pstmt.setString(3, "JAVA");


pstmt.executeUpdate();

System.out.println("Teacher records inserted successfully.");

pstmt.close();
conn.close();
}

// Method to display teachers teaching JAVA


public static void displayJavaTeachers() throws SQLException {
// PostgreSQL database connection details
String url = "jdbc:postgresql://localhost:5432/dpu"; // Replace with your DB name
String user = "postgres"; // Replace with your DB username
String password = "postgres"; // Replace with your DB password

Connection conn = DriverManager.getConnection(url, user, password);

// SQL query to get teachers who teach JAVA


String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";
PreparedStatement pstmt = conn.prepareStatement(selectQuery);
pstmt.setString(1, "JAVA"); // Set parameter for JAVA subject

ResultSet rs = pstmt.executeQuery();

System.out.println("Teachers teaching JAVA:");


while (rs.next()) {
int tNo = rs.getInt("TNo");
String tName = rs.getString("TName");
String subject = rs.getString("Subject");
System.out.println("TNo: " + tNo + ", TName: " + tName + ", Subject: " + subject);
}

rs.close();
pstmt.close();
conn.close();
}

public static void main(String[] args) {


try {
// Insert teacher records into the database
insertTeachers();

// Display teachers who are teaching JAVA


displayJavaTeachers();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
============================================================================================
/*
Write a Java program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).
*/

import java.sql.*;
public class DatabaseInfo {

public static void main(String[] args) {


// PostgreSQL database connection details
String url = "jdbc:postgresql://localhost:5432/dpu"; // Your database name (dpu)
String user = "postgres"; // Your PostgreSQL username
String password = "postgres"; // Your PostgreSQL password

Connection conn = null;


DatabaseMetaData metaData = null;

try {
// Establish the database connection
conn = DriverManager.getConnection(url, user, password);

// Get DatabaseMetaData object


metaData = conn.getMetaData();
// Display database information
System.out.println("Database Information:");
System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
System.out.println("Driver Name: " + metaData.getDriverName());
System.out.println("Driver Version: " + metaData.getDriverVersion());
System.out.println("Max Connections: " + metaData.getMaxConnections());

// Get the list of all tables in the database


System.out.println("\nList of Tables:");
ResultSet rs = metaData.getTables(null, null, "%", new String[] {"TABLE"});
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
System.out.println(tableName);
}

rs.close(); // Close the result set

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close(); // Close the connection
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a Java program to accept the details of Employee (Eno, EName, Designation, Salary)
from a user and store it into the database. (Use Swing).
*/
package com.sqltest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class EmployeeForm {

// JDBC URL, username, and password


static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";

public static void main(String[] args) {


// Create the frame for the form
JFrame frame = new JFrame("Employee Form");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a panel to hold the form components
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 2));

// Create the labels and text fields for Employee details


JLabel enoLabel = new JLabel("Employee No:");
JLabel enameLabel = new JLabel("Employee Name:");
JLabel designationLabel = new JLabel("Designation:");
JLabel salaryLabel = new JLabel("Salary:");

JTextField enoField = new JTextField();


JTextField enameField = new JTextField();
JTextField designationField = new JTextField();
JTextField salaryField = new JTextField();

// Add the labels and text fields to the panel


panel.add(enoLabel);
panel.add(enoField);
panel.add(enameLabel);
panel.add(enameField);
panel.add(designationLabel);
panel.add(designationField);
panel.add(salaryLabel);
panel.add(salaryField);

// Create the "Save" button and add an action listener to it


JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the input values
int eno = Integer.parseInt(enoField.getText());
String ename = enameField.getText();
String designation = designationField.getText();
double salary = Double.parseDouble(salaryField.getText());

// Save the employee data to the database


saveEmployeeToDatabase(eno, ename, designation, salary);
}
});

// Add the "Save" button to the panel


panel.add(saveButton);

// Add the panel to the frame and set it visible


frame.add(panel);
frame.setVisible(true);
}

// Method to save employee details into the database


public static void saveEmployeeToDatabase(int eno, String ename, String designation, double salary) {
Connection conn = null;
PreparedStatement pstmt = null;

try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// SQL query to insert employee data into the Employee table


String sql = "INSERT INTO Employee (Eno, EName, Designation, Salary) VALUES (?, ?, ?, ?)";

// Prepare the statement


pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, eno);
pstmt.setString(2, ename);
pstmt.setString(3, designation);
pstmt.setDouble(4, salary);

// Execute the update


pstmt.executeUpdate();

// Show a message on successful insertion


JOptionPane.showMessageDialog(null, "Employee details saved successfully!");

} catch (SQLException e) {
// Handle database errors
JOptionPane.showMessageDialog(null, "Error saving employee details: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

============================================================================================
/*
Write a java program for the following:
I. To create a Product(Pid, Pname, Price) table.
ii. Insert at least five records into the table.
iii. Display all the records from a table.
*/

package com.sqltest;
import java.sql.*;
public class ProductDatabase {
// JDBC URL, username, and password
static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";
public static void main(String[] args) {
// Creating Product Table
createProductTable();
// Inserting Product Records
insertProductRecords();
// Displaying Product Records
displayAllProducts();
}
// Method to create Product table
public static void createProductTable() {
Connection conn = null;
Statement stmt = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// SQL query to create Product table
String createTableSQL = "CREATE TABLE IF NOT EXISTS Product (" +
"Pid INT PRIMARY KEY, " +
"Pname VARCHAR(100), " +
"Price DECIMAL(10, 2))";
// Execute the query
stmt.executeUpdate(createTableSQL);
System.out.println("Product table created successfully!");
} catch (SQLException e) {
System.out.println("Error creating table: " + e.getMessage());
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method to insert records into the Product table
public static void insertProductRecords() {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// SQL query to insert product records
String insertSQL = "INSERT INTO Product (Pid, Pname, Price) VALUES (?, ?, ?)";
// Prepare statement
pstmt = conn.prepareStatement(insertSQL);
// Inserting 5 product records
pstmt.setInt(1, 101); pstmt.setString(2, "Laptop"); pstmt.setDouble(3, 50000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 102); pstmt.setString(2, "Smartphone"); pstmt.setDouble(3, 30000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 103); pstmt.setString(2, "Headphones"); pstmt.setDouble(3, 1500.00);
pstmt.executeUpdate();
pstmt.setInt(1, 104); pstmt.setString(2, "Smartwatch"); pstmt.setDouble(3, 8000.00);
pstmt.executeUpdate();
pstmt.setInt(1, 105); pstmt.setString(2, "Tablet"); pstmt.setDouble(3, 25000.00);
pstmt.executeUpdate();
System.out.println("Product records inserted successfully!");
} catch (SQLException e) {
System.out.println("Error inserting records: " + e.getMessage());
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method to display all product records
public static void displayAllProducts() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
// SQL query to get all products
String selectSQL = "SELECT * FROM Product";
// Execute query and get result set
rs = stmt.executeQuery(selectSQL);
// Displaying product records
System.out.println("Product Records:");
while (rs.next()) {
int pid = rs.getInt("Pid");
String pname = rs.getString("Pname");
double price = rs.getDouble("Price");
System.out.println("Pid: " + pid + ", Pname: " + pname + ", Price: " + price);
}
} catch (SQLException e) {
System.out.println("Error displaying records: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a java program to display information about all columns in the DONAR table using
ResultSetMetaData.
*/

package com.sqltest;
import java.sql.*;
public class DonarTableMetaData {
// JDBC URL, username, and password
static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rsMetaData = null;
try {
// Establish connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Create a statement
stmt = conn.createStatement();
// Execute the query to select all data from the DONAR table
rs = stmt.executeQuery("SELECT * FROM DONAR");
// Get ResultSetMetaData object
rsMetaData = rs.getMetaData();
// Get the number of columns in the DONAR table
int columnCount = rsMetaData.getColumnCount();
// Display column information
System.out.println("Column Information for the DONAR Table:");
for (int i = 1; i <= columnCount; i++) {
String columnName = rsMetaData.getColumnName(i);
int columnType = rsMetaData.getColumnType(i);
String columnTypeName = rsMetaData.getColumnTypeName(i);
int columnSize = rsMetaData.getColumnDisplaySize(i);
String nullable = rsMetaData.isNullable(i) == ResultSetMetaData.columnNullable ? "Nullable" : "Not
Nullable";
// Display each column's details
System.out.println("Column " + i + ":");
System.out.println(" Name: " + columnName);
System.out.println(" Type: " + columnTypeName + " (" + columnType + ")");
System.out.println(" Size: " + columnSize);
System.out.println(" Nullable: " + nullable);
System.out.println("----------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================

/*
Write a Java program to display first record from student table (RNo, SName, Per) onto the
TextField by clicking on button.(Assume Student table is already cerated)
*/
package com.sqltest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentRecordDisplay {

// JDBC URL, username, and password


static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";

public static void main(String[] args) {


// Create the JFrame for the GUI
JFrame frame = new JFrame("Student Record Display");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the panel to hold components


JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));

// Create labels and text fields for displaying the student record
JLabel rnoLabel = new JLabel("Roll No:");
JLabel snameLabel = new JLabel("Student Name:");
JLabel perLabel = new JLabel("Percentage:");

JTextField rnoField = new JTextField();


JTextField snameField = new JTextField();
JTextField perField = new JTextField();

// Create a button to fetch and display the first record


JButton displayButton = new JButton("Display First Record");

// Add labels, text fields, and button to the panel


panel.add(rnoLabel);
panel.add(rnoField);
panel.add(snameLabel);
panel.add(snameField);
panel.add(perLabel);
panel.add(perField);
panel.add(new JLabel()); // Empty label for spacing
panel.add(displayButton);

// Add the panel to the frame


frame.add(panel);
frame.setVisible(true);

// Add an action listener to the displayButton


displayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Call method to display the first student record in the text fields
displayFirstStudentRecord(rnoField, snameField, perField);
}
});
}
// Method to display the first student record from the database
public static void displayFirstStudentRecord(JTextField rnoField, JTextField snameField, JTextField perField) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Create a statement
stmt = conn.createStatement();

// Execute query to get the first student record


String query = "SELECT * FROM Student LIMIT 1";
rs = stmt.executeQuery(query);

// If the record exists, display it in the text fields


if (rs.next()) {
int rno = rs.getInt("RNo");
String sname = rs.getString("SName");
double per = rs.getDouble("Per");

// Set the values to the corresponding text fields


rnoField.setText(String.valueOf(rno));
snameField.setText(sname);
perField.setText(String.valueOf(per));
} else {
// If no records found
JOptionPane.showMessageDialog(null, "No records found in the Student table.");
}

} catch (SQLException e) {
// Handle database errors
JOptionPane.showMessageDialog(null, "Error fetching record: " + e.getMessage());
e.printStackTrace();
} finally {
try {
// Close resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
============================================================================================
/*
Write a Java Program to create a PROJECT table with field's project_id, Project_name,
Project_description, Project_Status. Insert values in the table. Display all the details of the
PROJECT table in a tabular format on the screen. (using swing).
*/
package com.sqltest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.DefaultTableModel;

public class ProjectTableApp {

// JDBC URL, username, and password


static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";

public static void main(String[] args) {


// Create the JFrame for the GUI
JFrame frame = new JFrame("PROJECT Table Viewer");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel for buttons and table display


JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());

// Create a button to load data from the PROJECT table


JButton loadButton = new JButton("Load Project Data");
panel.add(loadButton, BorderLayout.NORTH);

// Create JTable to display project records


String[] columns = {"Project ID", "Project Name", "Project Description", "Project Status"};
DefaultTableModel tableModel = new DefaultTableModel(columns, 0);
JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);

// Add the panel to the frame


frame.add(panel);
frame.setVisible(true);

// ActionListener for the Load button


loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Load the project records when the button is clicked
loadProjectData(tableModel);
}
});

// Create the PROJECT table and insert sample data (if not already created)
createAndInsertProjectData();
}

// Method to create the PROJECT table and insert sample data


public static void createAndInsertProjectData() {
Connection conn = null;
Statement stmt = null;

try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();

// SQL query to create the PROJECT table


String createTableSQL = "CREATE TABLE IF NOT EXISTS PROJECT (" +
"project_id SERIAL PRIMARY KEY, " +
"project_name VARCHAR(100), " +
"project_description TEXT, " +
"project_status VARCHAR(50))";
stmt.executeUpdate(createTableSQL);

// Insert sample records into the PROJECT table


String insertSQL = "INSERT INTO PROJECT (project_name, project_description, project_status) VALUES " +
"('Project A', 'This is the description for Project A', 'Ongoing')," +
"('Project B', 'This is the description for Project B', 'Completed')," +
"('Project C', 'This is the description for Project C', 'Not Started')";
stmt.executeUpdate(insertSQL);

System.out.println("PROJECT table created and sample data inserted successfully!");

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

// Method to load data from the PROJECT table and display it in the JTable
public static void loadProjectData(DefaultTableModel tableModel) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Establish connection to the database
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();

// SQL query to retrieve all records from the PROJECT table


String selectSQL = "SELECT * FROM PROJECT";
rs = stmt.executeQuery(selectSQL);

// Clear existing rows in the table model


tableModel.setRowCount(0);

// Iterate through the result set and add rows to the table model
while (rs.next()) {
int projectId = rs.getInt("project_id");
String projectName = rs.getString("project_name");
String projectDescription = rs.getString("project_description");
String projectStatus = rs.getString("project_status");

// Add row to the table model


tableModel.addRow(new Object[]{projectId, projectName, projectDescription, projectStatus});
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

============================================================================================
/*
Write a Menu Driven program in Java for the following: Assume Employee table with
attributes (ENo, EName, Salary) is already created. 1. Insert 2. Update 3. Display 4. Exit.
*/

import java.sql.*;
import java.util.Scanner;

public class EmployeeMenuApp {

// JDBC URL, username, and password


static final String DB_URL = "jdbc:postgresql://localhost:5432/dpu";
static final String USER = "postgres";
static final String PASS = "postgres";

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

do {
// Display menu options
System.out.println("Menu:");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

// Switch statement to handle the menu options


switch (choice) {
case 1:
insertEmployee(scanner);
break;
case 2:
updateEmployee(scanner);
break;
case 3:
displayEmployees();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 4);

scanner.close();
}

// Method to insert an employee record into the Employee table


public static void insertEmployee(Scanner scanner) {
System.out.print("Enter Employee Number (ENo): ");
int eno = scanner.nextInt();
scanner.nextLine(); // Consume newline left by nextInt
System.out.print("Enter Employee Name (EName): ");
String ename = scanner.nextLine();
System.out.print("Enter Salary: ");
double salary = scanner.nextDouble();

Connection conn = null;


PreparedStatement stmt = null;

try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// SQL query to insert data


String insertSQL = "INSERT INTO Employee (ENo, EName, Salary) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(insertSQL);

// Set parameters
stmt.setInt(1, eno);
stmt.setString(2, ename);
stmt.setDouble(3, salary);

// Execute the query


int rowsAffected = stmt.executeUpdate();

if (rowsAffected > 0) {
System.out.println("Employee record inserted successfully!");
} else {
System.out.println("Failed to insert employee record.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

// Method to update an employee's salary in the Employee table


public static void updateEmployee(Scanner scanner) {
System.out.print("Enter Employee Number (ENo) to update: ");
int eno = scanner.nextInt();
System.out.print("Enter new Salary: ");
double newSalary = scanner.nextDouble();

Connection conn = null;


PreparedStatement stmt = null;

try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// SQL query to update employee salary


String updateSQL = "UPDATE Employee SET Salary = ? WHERE ENo = ?";
stmt = conn.prepareStatement(updateSQL);

// Set parameters
stmt.setDouble(1, newSalary);
stmt.setInt(2, eno);

// Execute the update query


int rowsAffected = stmt.executeUpdate();

if (rowsAffected > 0) {
System.out.println("Employee salary updated successfully!");
} else {
System.out.println("No employee found with the given ENo.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

// Method to display all employee records from the Employee table


public static void displayEmployees() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();

// SQL query to fetch all employee records


String selectSQL = "SELECT * FROM Employee";
rs = stmt.executeQuery(selectSQL);

// Display the results in tabular format


System.out.println("Employee Records:");
System.out.println("ENo\tEName\t\tSalary");
System.out.println("-----------------------------------");

while (rs.next()) {
int eno = rs.getInt("ENo");
String ename = rs.getString("EName");
double salary = rs.getDouble("Salary");
System.out.println(eno + "\t" + ename + "\t\t" + salary);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

===========================================================================================

You might also like