Untitled Document
Untitled Document
Aim;
To implement JDBC concepts on a case study.
Program:
import java.sql.*;
private static void insertRecord(Connection con, int custNum, String company, int custRep, int
creditLimit) throws SQLException {
String insertSQL = "INSERT INTO CUSTOMERS (CUST_NUM, COMPANY, CUST_REP,
CREDIT_LIMIT) VALUES (?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(insertSQL)) {
pstmt.setInt(1, custNum);
pstmt.setString(2, company);
pstmt.setInt(3, custRep);
pstmt.setInt(4, creditLimit);
pstmt.executeUpdate();
System.out.println("Record inserted successfully.");
}
}
private static void updateRecord(Connection con, int custNum, String newCompany, int
newCustRep, int newCreditLimit) throws SQLException {
String updateSQL = "UPDATE CUSTOMERS SET COMPANY = ?, CUST_REP = ?,
CREDIT_LIMIT = ? WHERE CUST_NUM = ?";
try (PreparedStatement pstmt = con.prepareStatement(updateSQL)) {
pstmt.setString(1, newCompany);
pstmt.setInt(2, newCustRep);
pstmt.setInt(3, newCreditLimit);
pstmt.setInt(4, custNum);
pstmt.executeUpdate();
System.out.println("Record updated successfully.");
}
}
private static void deleteRecord(Connection con, int custNum) throws SQLException {
String deleteSQL = "DELETE FROM CUSTOMERS WHERE CUST_NUM = ?";
try (PreparedStatement pstmt = con.prepareStatement(deleteSQL)) {
pstmt.setInt(1, custNum);
pstmt.executeUpdate();
System.out.println("Record deleted successfully.");
}
}
}
Output:
Table CUSTOMERS created successfully.
Record inserted successfully.
Record inserted successfully.
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 Company A 101 5000
2 Company B 102 6000
Record inserted successfully.
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 Company A 101 5000
2 Company B 102 6000
3 Company C 103 8000
Record updated successfully.
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 Company A 101 5000
2 Company B 102 6000
3 Updated Company C 104 9000
Record deleted successfully.
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
1 Company A 101 5000
2 Company B 102 6000