Java Reference
In-Depth Information
LISTING 18.3
Continued
59: result = st.executeUpdate(
60: “INSERT INTO contacts (name, address1, address2, “
61: + “phone, email) VALUES(“
62: + “'George W. Bush', “
63: + “'White House, 1600 Pennsylvania Ave.', “
64: + “'Washington, DC 20500', “
65: + “'(202) 456-1414', “
66: + “'president@whitehouse.gov')”);
67: st.close();
68: System.out.println(“Database created in “ + system);
69: } catch (Exception e) {
70: System.out.println(“Error — “ + e.toString());
71: }
72: }
73:
74: public void readDatabase() {
75: String data = “jdbc:derby:presidents”;
76: try {
77: // load the driver and connect to the database
78: Class.forName(“org.apache.derby.jdbc.EmbeddedDriver”);
79: Connection conn = DriverManager.getConnection(
80: data, “”, “”);
81: // load all records from the contacts table
82: Statement st = conn.createStatement();
83: ResultSet rec = st.executeQuery(
84: “SELECT * FROM contacts ORDER BY name”);
85: // loop through each record and display its fields
86: while(rec.next()) {
87: System.out.println(rec.getString(“name”) + “\n”
88: + rec.getString(“address1”) + “\n”
89: + rec.getString(“address2”) + “\n”
90: + rec.getString(“phone”) + “\n”
91: + rec.getString(“email”) + “\n”);
92: }
93: st.close();
94: } catch (Exception e) {
95: System.out.println(“Error — “ + e.toString());
96: }
97: }
98:
99: public static void main(String[] arguments) {
100: Presidents prez = new Presidents();
101: if (arguments.length < 1) {
102: System.out.println(“Usage: java Presidents [create|read]”);
103: System.exit(-1);
104: }
105: if (arguments[0].equals(“create”)) {
106: prez.createDatabase();
107: }
18
Search WWH ::




Custom Search