J Worksheet 11 Database Connectivity
J Worksheet 11 Database Connectivity
Lab Worksheet 11
Object Oriented Programming
Java Program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
while (rs.next()) {
System.out.println("ID: " + rs.getString("Aid") + ", Name: " +
rs.getString("name") +", Ph Number " + rs.getInt("ph_num")+ ", Acc Type: " +
rs.getString("Account_type")+ ", Balance: " + rs.getInt("Balance"));
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found. Include it in your
library path.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed! Check output console");
e.printStackTrace();
}
}
}
Compilation
import java.sql.*;
import java.util.Scanner;
while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Insert into Account");
System.out.println("2. Update Account Balance");
System.out.println("3. Insert into Person");
System.out.println("4. Update Person Details");
System.out.println("5. Insert into Holds");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
insertAccount(conn, scanner);
break;
case 2:
updateAccountBalance(conn, scanner);
break;
case 3:
insertPerson(conn, scanner);
break;
case 4:
updatePersonDetails(conn, scanner);
break;
case 5:
insertHolds(conn, scanner);
break;
case 6:
System.out.println("Exiting program...");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
String sql = "INSERT INTO Person (Aid, name, age, ph_num, email)
VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, aid);
pstmt.setString(2, name);
pstmt.setInt(3, age);
pstmt.setLong(4, phone);
pstmt.setString(5, email);
pstmt.executeUpdate();
System.out.println("Person inserted successfully.");
}
}
String sql = "UPDATE Person SET ph_num = ?, email = ? WHERE Aid = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setLong(1, newPhone);
pstmt.setString(2, newEmail);
pstmt.setString(3, aid);
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Person details updated successfully.");
} else {
System.out.println("Person not found.");
}
}
}
String sql = "INSERT INTO Holds (Account_num, Aid) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, accountNum);
pstmt.setString(2, aid);
pstmt.executeUpdate();
System.out.println("Holds record inserted successfully.");
}
}
}
Compilation