package io.trygvis.container.myapp; import java.io.BufferedReader; import java.io.EOFException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class AddressBook { private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws Exception { try { new AddressBook().work(); } catch (EOFException ignore) { } } private void work() throws Exception { boolean done = false; while (!done) { String cmd = Character.toString(menu()); switch (cmd) { case "c": run(new CreateTablesCommand()); break; case "d": run(new DropTablesCommand()); break; case "a": run(new AddCommand()); break; case "l": run(new ListCommand()); break; case "q": done = true; break; default: System.out.println("Unknown command: " + cmd); } } } private String line() throws Exception { String line = reader.readLine(); if(line == null) { throw new EOFException(); } return line.trim(); } public static interface Command { void run(Connection c) throws Exception; } public void run(Command command) throws Exception { try (Connection c = DriverManager.getConnection("jdbc:h2:mem:address-book;DB_CLOSE_DELAY=-1")) { c.setAutoCommit(false); command.run(c); c.commit(); System.out.println("OK"); } } private char menu() throws Exception { System.out.println("Menu:"); System.out.println("c Create"); System.out.println("d Drop"); System.out.println("l List"); System.out.println("a Add"); System.out.println("q Quit"); while (true) { String read = line(); if (read.length() != 0) { return read.charAt(0); } } } public static class CreateTablesCommand implements Command { @Override public void run(Connection c) throws Exception { Statement statement = c.createStatement(); statement.executeUpdate(PersonDao.createTableSql); } } public static class DropTablesCommand implements Command { @Override public void run(Connection c) throws Exception { Statement statement = c.createStatement(); statement.executeUpdate(PersonDao.dropTableSql); } } public class AddCommand implements Command { @Override public void run(Connection c) throws Exception { System.out.print("Name: "); String name = line(); Person o = new Person(name); PersonDao.insertInto(c, o); } } public static class ListCommand implements Command { @Override public void run(Connection c) throws Exception { // PersonDao.insertInto(c, new Person()); } } }