KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > WwdClientExample


1 /* WwdClientExample.java
2  ** This sample program is described in the document Working With Derby
3
4        Licensed to the Apache Software Foundation (ASF) under one
5            or more contributor license agreements. See the NOTICE file
6            distributed with this work for additional information
7            regarding copyright ownership. The ASF licenses this file
8            to you under the Apache License, Version 2.0 (the
9            "License"); you may not use this file except in compliance
10            with the License. You may obtain a copy of the License at
11
12              http://www.apache.org/licenses/LICENSE-2.0
13
14            Unless required by applicable law or agreed to in writing,
15            software distributed under the License is distributed on an
16            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17            KIND, either express or implied. See the License for the
18            specific language governing permissions and limitations
19            under the License.
20 */

21 // ## INITIALIZATION SECTION ##
22
// Include the java SQL classes
23
import java.sql.*;
24
25 public class WwdClientExample
26 {
27     public static void main(String JavaDoc[] args)
28    {
29    // ## DEFINE VARIABLES SECTION ##
30
// define the driver to use
31
String JavaDoc driver = "org.apache.derby.jdbc.ClientDriver";
32    // the database name
33
String JavaDoc dbName="jdbcDemoDB";
34    // define the Derby connection URL to use
35
String JavaDoc connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
36
37       Connection conn = null;
38       Statement s;
39       PreparedStatement psInsert;
40       ResultSet myWishes;
41       String JavaDoc printLine = " __________________________________________________";
42       String JavaDoc createString = "CREATE TABLE WISH_LIST "
43         + "(WISH_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY "
44         + " CONSTRAINT WISH_PK PRIMARY KEY, "
45         + " ENTRY_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
46         + " WISH_ITEM VARCHAR(32) NOT NULL) " ;
47       String JavaDoc answer;
48
49       // Beginning of JDBC code sections
50
// ## LOAD DRIVER SECTION ##
51
try {
52           /*
53           ** Load the Derby driver.
54           ** When the embedded Driver is used this action start the Derby engine.
55           ** Catch an error and suggest a CLASSPATH problem
56            */

57           Class.forName(driver);
58           System.out.println(driver + " loaded. ");
59       } catch(java.lang.ClassNotFoundException JavaDoc e) {
60           System.err.print("ClassNotFoundException: ");
61           System.err.println(e.getMessage());
62           System.out.println("\n >>> Please check your CLASSPATH variable <<<\n");
63       }
64       // Beginning of Primary DB access section
65
// ## BOOT DATABASE SECTION ##
66
try {
67             // Create (if needed) and connect to the database
68
conn = DriverManager.getConnection(connectionURL);
69             System.out.println("Connected to database " + dbName);
70             
71             // ## INITIAL SQL SECTION ##
72
// Create a statement to issue simple commands.
73
s = conn.createStatement();
74              // Call utility method to check if table exists.
75
// Create the table if needed
76
if (! WwdUtils.wwdChk4Table(conn))
77              {
78                   System.out.println (" . . . . creating table WISH_LIST");
79                   s.execute(createString);
80               }
81              // Prepare the insert statement to use
82
psInsert = conn.prepareStatement("insert into WISH_LIST(WISH_ITEM) values (?)");
83
84             // ## ADD / DISPLAY RECORD SECTION ##
85
// The Add-Record Loop - continues until 'exit' is entered
86
do {
87                 // Call utility method to ask user for input
88
answer = WwdUtils.getWishItem();
89                 // Check if it is time to EXIT, if not insert the data
90
if (! answer.equals("exit"))
91                 {
92                     //Insert the text entered into the WISH_ITEM table
93
psInsert.setString(1,answer);
94                     psInsert.executeUpdate();
95
96                     // Select all records in the WISH_LIST table
97
myWishes = s.executeQuery("select ENTRY_DATE, WISH_ITEM from WISH_LIST order by ENTRY_DATE");
98
99                     // Loop through the ResultSet and print the data
100
System.out.println(printLine);
101                     while (myWishes.next())
102                      {
103                            System.out.println("On " + myWishes.getTimestamp(1) + " I wished for " + myWishes.getString(2));
104                       }
105                       System.out.println(printLine);
106                       // Close the resultSet
107
myWishes.close();
108                  } // END of IF block
109
// Check if it is time to EXIT, if so end the loop
110
} while (! answer.equals("exit")) ; // End of do-while loop
111

112              // Release the resources (clean up )
113
psInsert.close();
114              s.close();
115             conn.close();
116             System.out.println("Closed connection");
117
118             // ## DATABASE SHUTDOWN SECTION ##
119
/*** In embedded mode, an application should shut down Derby.
120                Shutdown throws the XJ015 exception to confirm success. ***/

121             if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) {
122                boolean gotSQLExc = false;
123                try {
124                   DriverManager.getConnection("jdbc:derby:;shutdown=true");
125                } catch (SQLException se) {
126                   if ( se.getSQLState().equals("XJ015") ) {
127                      gotSQLExc = true;
128                   }
129                }
130                if (!gotSQLExc) {
131                   System.out.println("Database did not shut down normally");
132                } else {
133                   System.out.println("Database shut down normally");
134                }
135             }
136             
137          // Beginning of the primary catch block: uses errorPrint method
138
} catch (Throwable JavaDoc e) {
139             /* Catch all exceptions and pass them to
140             ** the exception reporting method */

141             System.out.println(" . . . exception thrown:");
142             errorPrint(e);
143          }
144          System.out.println("Working With Derby JDBC program ending.");
145       }
146      // ## DERBY EXCEPTION REPORTING CLASSES ##
147
/*** Exception reporting methods
148     ** with special handling of SQLExceptions
149     ***/

150       static void errorPrint(Throwable JavaDoc e) {
151          if (e instanceof SQLException)
152             SQLExceptionPrint((SQLException)e);
153          else {
154             System.out.println("A non SQL error occured.");
155             e.printStackTrace();
156          }
157       } // END errorPrint
158

159     // Iterates through a stack of SQLExceptions
160
static void SQLExceptionPrint(SQLException sqle) {
161          while (sqle != null) {
162             System.out.println("\n---SQLException Caught---\n");
163             System.out.println("SQLState: " + (sqle).getSQLState());
164             System.out.println("Severity: " + (sqle).getErrorCode());
165             System.out.println("Message: " + (sqle).getMessage());
166             sqle.printStackTrace();
167             sqle = sqle.getNextException();
168          }
169    } // END SQLExceptionPrint
170
}
171
Popular Tags