No Java programmer is complete without knowledge of Java database connectivity, or JDBC for short. In this 2 part article Nitin teaches us JDBC from the inside out.
/** Adds an entry to the addressbook. Returns 1 if the entry is added successfully. */ public int add(Connection con, String nickName, String name, String email) throws SQLException {
// Get a database connection con = jdbcDemo.getConnection();
// Obtain a reader for reading standard input for convenience in = new BufferedReader(new InputStreamReader(System.in));
while(continueFlag) {
System.out.println(); System.out.println(); System.out.println(" *** Address Book Menu ***"); System.out.println(); System.out.println("Choose your option from 1-4 below"); System.out.println("1. Create the addressbook table"); System.out.println("2. Add an entry to the addressbook"); System.out.println("3. Search an entry in the addressbook"); System.out.println("4. Quit"); System.out.print("Enter your choice [1-4]: "); choiceStr = in.readLine();
try {
// Determine the option choice = Integer.parseInt(choiceStr);
// Handle option switch(choice) {
case 1: // Create table jdbcDemo.createTable(con); printResult("Table created successfully."); break;
case 2: // Add an entry System.out.println("Enter the following information."); System.out.print("Nickname: "); nickName = in.readLine(); System.out.print("Name: "); name = in.readLine(); System.out.print("Email: "); email = in.readLine(); jdbcDemo.add(con, nickName, name, email); printResult("Entry added successfully."); break;
case 3: // Search an entry System.out.print("Enter the nickname to search: "); nickName = in.readLine(); entry = jdbcDemo.lookup(con, nickName); if (entry != null) { printResult(entry.toString()); } else { printResult("No such nickname in the addressbook."); } break;
// Clean up try { if (con != null) { con.close(); } } catch(SQLException ex) { }
// Check if it was a normal exit if (!continueFlag) { System.out.println(); System.out.println("Thank you for using the addressbook."); System.out.println(); }
}
}
/** Prints a result. */ public static void printResult(String msg) { System.out.println(); System.out.println("RESULT: " + msg); }