KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > WwdEmbedded


1 /*
2      Derby - WwdEmbedded.java ( 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 */

22 /*
23  ** This sample program is described in the document Working With Derby
24 */

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

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

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

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

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

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

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