KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SimpleApp


1 /*
2
3    Derby - Class SimpleApp
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    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, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 import java.sql.Connection JavaDoc;
23 import java.sql.DriverManager JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.sql.Statement JavaDoc;
27
28 import java.util.Properties JavaDoc;
29
30
31 /**
32  * This sample program is a minimal JDBC application showing
33  * JDBC access to Derby.
34  *
35  * Instructions for how to run this program are
36  * given in <A HREF=example.html>example.html</A>.
37  *
38  * Derby applications can run against Derby running in an embedded
39  * or a client/server framework. When Derby runs in an embedded framework,
40  * the Derby application and Derby run in the same JVM. The application
41  * starts up the Derby engine. When Derby runs in a client/server framework,
42  * the application runs in a different JVM from Derby. The application only needs
43  * to start the client driver, and the connectivity framework provides network connections.
44  * (The server must already be running.)
45  *
46  * <p>When you run this application, give one of the following arguments:
47  * * embedded (default, if none specified)
48  * * derbyclient (will use the Net client driver to access Network Server)
49  * * jccjdbcclient (if Derby is running embedded in the JCC Server framework)
50  *
51  * @author janet
52  */

53 public class SimpleApp
54 {
55     /* the default framework is embedded*/
56     public String JavaDoc framework = "embedded";
57     public String JavaDoc driver = "org.apache.derby.jdbc.EmbeddedDriver";
58     public String JavaDoc protocol = "jdbc:derby:";
59
60     public static void main(String JavaDoc[] args)
61     {
62         new SimpleApp().go(args);
63     }
64
65     void go(String JavaDoc[] args)
66     {
67         /* parse the arguments to determine which framework is desired*/
68         parseArguments(args);
69
70         System.out.println("SimpleApp starting in " + framework + " mode.");
71
72         try
73         {
74             /*
75                The driver is installed by loading its class.
76                In an embedded environment, this will start up Derby, since it is not already running.
77              */

78             Class.forName(driver).newInstance();
79             System.out.println("Loaded the appropriate driver.");
80
81             Connection JavaDoc conn = null;
82             Properties JavaDoc props = new Properties JavaDoc();
83             props.put("user", "user1");
84             props.put("password", "user1");
85
86             /*
87                The connection specifies create=true to cause
88                the database to be created. To remove the database,
89                remove the directory derbyDB and its contents.
90                The directory derbyDB will be created under
91                the directory that the system property
92                derby.system.home points to, or the current
93                directory if derby.system.home is not set.
94              */

95             conn = DriverManager.getConnection(protocol +
96                     "derbyDB;create=true", props);
97
98             System.out.println("Connected to and created database derbyDB");
99
100             conn.setAutoCommit(false);
101
102             /*
103                Creating a statement lets us issue commands against
104                the connection.
105              */

106             Statement JavaDoc s = conn.createStatement();
107
108             /*
109                We create a table, add a few rows, and update one.
110              */

111             s.execute("create table derbyDB(num int, addr varchar(40))");
112             System.out.println("Created table derbyDB");
113             s.execute("insert into derbyDB values (1956,'Webster St.')");
114             System.out.println("Inserted 1956 Webster");
115             s.execute("insert into derbyDB values (1910,'Union St.')");
116             System.out.println("Inserted 1910 Union");
117             s.execute(
118                 "update derbyDB set num=180, addr='Grand Ave.' where num=1956");
119             System.out.println("Updated 1956 Webster to 180 Grand");
120
121             s.execute(
122                 "update derbyDB set num=300, addr='Lakeshore Ave.' where num=180");
123             System.out.println("Updated 180 Grand to 300 Lakeshore");
124
125             /*
126                We select the rows and verify the results.
127              */

128             ResultSet JavaDoc rs = s.executeQuery(
129                     "SELECT num, addr FROM derbyDB ORDER BY num");
130
131             if (!rs.next())
132             {
133                 throw new Exception JavaDoc("Wrong number of rows");
134             }
135
136             if (rs.getInt(1) != 300)
137             {
138                 throw new Exception JavaDoc("Wrong row returned");
139             }
140
141             if (!rs.next())
142             {
143                 throw new Exception JavaDoc("Wrong number of rows");
144             }
145
146             if (rs.getInt(1) != 1910)
147             {
148                 throw new Exception JavaDoc("Wrong row returned");
149             }
150
151             if (rs.next())
152             {
153                 throw new Exception JavaDoc("Wrong number of rows");
154             }
155
156             System.out.println("Verified the rows");
157
158             s.execute("drop table derbyDB");
159             System.out.println("Dropped table derbyDB");
160
161             /*
162                We release the result and statement resources.
163              */

164             rs.close();
165             s.close();
166             System.out.println("Closed result set and statement");
167
168             /*
169                We end the transaction and the connection.
170              */

171             conn.commit();
172             conn.close();
173             System.out.println("Committed transaction and closed connection");
174
175             /*
176                In embedded mode, an application should shut down Derby.
177                If the application fails to shut down Derby explicitly,
178                the Derby does not perform a checkpoint when the JVM shuts down, which means
179                that the next connection will be slower.
180                Explicitly shutting down Derby with the URL is preferred.
181                This style of shutdown will always throw an "exception".
182              */

183             boolean gotSQLExc = false;
184
185             if (framework.equals("embedded"))
186             {
187                 try
188                 {
189                     DriverManager.getConnection("jdbc:derby:;shutdown=true");
190                 }
191                 catch (SQLException JavaDoc se)
192                 {
193                     gotSQLExc = true;
194                 }
195
196                 if (!gotSQLExc)
197                 {
198                     System.out.println("Database did not shut down normally");
199                 }
200                 else
201                 {
202                     System.out.println("Database shut down normally");
203                 }
204             }
205         }
206         catch (Throwable JavaDoc e)
207         {
208             System.out.println("exception thrown:");
209
210             if (e instanceof SQLException JavaDoc)
211             {
212                 printSQLError((SQLException JavaDoc) e);
213             }
214             else
215             {
216                 e.printStackTrace();
217             }
218         }
219
220         System.out.println("SimpleApp finished");
221     }
222
223     static void printSQLError(SQLException JavaDoc e)
224     {
225         while (e != null)
226         {
227             System.out.println(e.toString());
228             e = e.getNextException();
229         }
230     }
231
232     private void parseArguments(String JavaDoc[] args)
233     {
234         int length = args.length;
235
236         for (int index = 0; index < length; index++)
237         {
238             if (args[index].equalsIgnoreCase("jccjdbcclient"))
239             {
240                 framework = "jccjdbc";
241                 driver = "com.ibm.db2.jcc.DB2Driver";
242                 protocol = "jdbc:derby:net://localhost:1527/";
243             }
244             if (args[index].equalsIgnoreCase("derbyclient"))
245             {
246                 framework = "derbyclient";
247                 driver = "org.apache.derby.jdbc.ClientDriver";
248                 protocol = "jdbc:derby://localhost:1527/";
249             }
250         }
251     }
252 }
253
Popular Tags