package bookstoreapp.clientside; import java.io.*; import java.sql.*; import java.util.*; public class Inventory { public static void main(String[] args) throws Exception { Class.forName("com.ibm.db2.jcc.DB2Driver"); String url = "jdbc:derby:net://localhost:1527/bookstoredb"; url += ":user=bookstore;password=aaa;"; url += "retrieveMessagesFromServerOnGetMessage=true;"; Connection con = DriverManager.getConnection(url); processCommands(con); con.close(); } public static void processCommands(Connection con) throws Exception { boolean end = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Statement stmt = con.createStatement(); while (!end) { System.out.print("> "); String cmd = in.readLine(); if (cmd.equals("quit")) end = true; else if (cmd.startsWith("list")) listBooks(stmt); else if (cmd.startsWith("add")) updateQuantity(stmt, cmd, true); else if (cmd.startsWith("remove")) updateQuantity(stmt, cmd, false); } stmt.close(); } protected static void listBooks(Statement stmt) throws Exception { ResultSet rs = stmt.executeQuery("SELECT * FROM books"); while (rs.next()) { System.out.print(rs.getString(1) + ", "); System.out.print(rs.getString(2) + ", "); System.out.print(rs.getString(3) + ", "); System.out.print(rs.getString(4) + ", "); System.out.print(rs.getString(5) + ", "); System.out.println(rs.getString(6)); } rs.close(); } protected static void updateQuantity(Statement stmt, String cmd, boolean add) throws Exception { StringTokenizer st = new StringTokenizer(cmd); st.nextToken(); // skip first token String id = st.nextToken(); String quantity = st.nextToken(); String query = "update books set quantity=quantity"; query += (add) ? "+" : "-"; query += quantity; query += " where id=" + id; stmt.executeUpdate(query); System.out.println("Updated"); } }