db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kahat...@apache.org
Subject svn commit: r597661 [1/2] - in /db/derby/code/trunk: java/demo/ java/demo/simple/ java/testing/org/apache/derbyTesting/functionTests/master/ tools/release/
Date Fri, 23 Nov 2007 13:32:07 GMT
Author: kahatlen
Date: Fri Nov 23 05:32:04 2007
New Revision: 597661

URL: http://svn.apache.org/viewvc?rev=597661&view=rev
Log:
DERBY-3118: Simple demo is out of date

  a) Eliminate errors and outdated information in documentation and code

  b) Eliminate Java code that is generally discouraged in the
     community, such as
        - catch (Throwable) {}
        - leaving resources open if an error occurs
        - not using PreparedStatement for repeated executions of the
          same SQL statement

  c) Make it easier for users to find the demos, especially the simple
     demo. More work is needed for other demos.

Patch contributed by John H. Embretsen.

Added:
    db/derby/code/trunk/java/demo/README.txt   (with props)
    db/derby/code/trunk/java/demo/derbylogo128_bluebg.png   (with props)
Modified:
    db/derby/code/trunk/java/demo/csfull.css
    db/derby/code/trunk/java/demo/demo.html
    db/derby/code/trunk/java/demo/navbar.html
    db/derby/code/trunk/java/demo/readme.html
    db/derby/code/trunk/java/demo/simple/SimpleApp.java
    db/derby/code/trunk/java/demo/simple/example.html
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/SimpleApp.out
    db/derby/code/trunk/tools/release/build.xml

Added: db/derby/code/trunk/java/demo/README.txt
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/README.txt?rev=597661&view=auto
==============================================================================
--- db/derby/code/trunk/java/demo/README.txt (added)
+++ db/derby/code/trunk/java/demo/README.txt Fri Nov 23 05:32:04 2007
@@ -0,0 +1,32 @@
+<DERBY_HOME>/demo/README.txt:
+
+Information about demos included in this distribution of Apache Derby
+=====================================================================
+
+This directory (<DERBY_HOME>/demo/) contains example programs and
+databases demonstrating different aspects of the Apache Derby
+database system, as well as templates for custom configuration.
+
+Please refer to "readme" or "example" files in the respective
+subdirectories for more information about each demo.
+
+You will find the following "demo" directories in some distributions
+of Apache Derby:
+
+demo/databases
+ - contains pre-built databases or other binary resources that are
+   used by demo programs or mentioned in Apache Derby documentation.
+
+demo/programs
+ - contains demo applications written in Java. Go here if you want
+   to see examples of how to use Derby in various contexts.
+ - Recommended starting point:
+    - Open demo/programs/readme.html in a web browser.
+
+demo/templates
+ - contains template files you can use to configure or tune Derby.
+
+
+-- -- --
+
+Apache Derby web site: http://db.apache.org/derby/

Propchange: db/derby/code/trunk/java/demo/README.txt
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/demo/csfull.css
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/csfull.css?rev=597661&r1=597660&r2=597661&view=diff
==============================================================================
--- db/derby/code/trunk/java/demo/csfull.css (original)
+++ db/derby/code/trunk/java/demo/csfull.css Fri Nov 23 05:32:04 2007
@@ -15,8 +15,8 @@
 * limitations under the License.
 */
 BODY {
-	font-size : 12pt;
-	font-family : "Times New Roman";
+	font-size : 10pt;
+	font-family : sans-serif;
 	background-color : White;
 }
 
@@ -25,15 +25,14 @@
 	background-color : transparent;
 }
 
-A:HOVER {
-	color : Fuchsia;
-	text-decoration : underline;
+A:VISITED {
+	color : #330099;
 	background-color : transparent;
 }
 
-	
-A:VISITED {
-	color : #330099;
+A:HOVER {
+	color : Teal;
+	text-decoration : underline;
 	background-color : transparent;
 }
 
@@ -49,25 +48,36 @@
 	background-color : transparent;
 }
 
-A.TOC:HOVER {
-	color : Fuchsia;
-	font-weight : bold;
-	background-color : transparent;
-}
-
-	
 A.TOC:VISITED {
 	color : #330099;
 	text-decoration : none;
 	background-color : transparent;
 }
 
+A.TOC:HOVER {
+	color : Fuchsia;
+	font-weight : bold;
+	background-color : transparent;
+}
+
 A.TOC:ACTIVE {
 	color : Purple;
 	text-decoration : none;
 	background-color : transparent;
 }
 
+a[id] {
+	/* All anchors with an id attribute get this style.
+	   Used to make sure internal links (links to a different section
+	   on the same page, i.e. named anchors) don't change appearance when
+	   hovering in CSS2-enabled browsers.
+	   Hence, links to other pages should not have the id attribute set,
+	   unless this particular solution is consciously abandoned.
+        */
+	color : #3300ff ! important;
+	text-decoration : none ! important;
+}
+
 .BadFormatting{
 	background-color : transparent;
 	font-size : 24pt;
@@ -82,6 +92,10 @@
 	font-size : 9pt;
 }
 
+.java {
+	background-color : transparent;
+	font-family: monospace;
+}
 
 .Output {
 	color : Gray;
@@ -124,6 +138,12 @@
 	font-weight : bold;
 }
 
+div.navMenu {
+	border-style: dashed;
+	border-width: thin;
+	border-color: #6699cc;
+}
+
 DL.Index {
 	font-size : 9pt;
 }
@@ -211,6 +231,7 @@
 }
 
 H3.BoxHead {
+	font-size : 90%;
 	margin-top : 1px;
 	margin-bottom : 6px;
 	color : Black;
@@ -303,7 +324,9 @@
 	margin-left : 2em;
 }
 
-
+IMG {
+	border : none;
+}
 
 LI{
 	margin-top : 12px;
@@ -465,10 +488,10 @@
 	font-size : 9pt;
 	margin-top:6px;
 	margin-bottom :6px;
-	padding-top : 2px;
+	padding-top : 2em;
 	padding-right : 2px;
 	padding-left : 2px;
-	padding-bottom : 2px;
+	padding-bottom : 2em;
 	background-color : transparent;
 }
 
@@ -646,15 +669,50 @@
 
 }
 
+PRE.Output {
+	background-color : transparent;
+	font-size : 10pt;
+	font-family : monospace;
+	color: gray;
+}
+
+TABLE.listing {
+	font-size : 100%;
+	background-color : #faf0e6;
+	border-style: solid;
+	border-color: silver;
+	border-width : 1px;
+}
+
 TABLE.Sample {
 	background-color : #FAF0E6;
 }
 
+TABLE.simple {
+	font-size : 100%;
+	border-style: solid;
+	border-width: 1px;
+	border-color: #6699cc;
+}
+
 TD.BoxTable {
 	background-color : Silver;
 	padding : 10px;
 }
 
+TD.listItem {
+	padding-top: 0.2em;
+	padding-bottom: 0.2em;
+	padding-left: 0.2em;
+	padding-right: 0.5em;
+}
+
+TD.heading {
+	font-weight : bold;
+	background-color : #6699cc;
+	color: #e7efff;
+}
+
 UL {
 	background-color : transparent;
 }
@@ -662,6 +720,11 @@
 	background-color : transparent;
 }
 
+UL.boxed {
+	background-color : transparent;
+	font-size : 9pt;
+	padding-bottom : 1em;
+}
 
 UL.CellBodyBulleted {
 	font-size : 10pt;
@@ -770,3 +833,18 @@
 	background-color : transparent;
 }
 
+var {
+	background-color : transparent;
+	color : Black;
+	font-weight : bold;
+	font-family : monospace;
+	font-size : 90%;
+}
+
+var.envVar {
+	font-style : normal;
+}
+
+var.property {
+	font-weight : normal;
+}

Modified: db/derby/code/trunk/java/demo/demo.html
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/demo.html?rev=597661&r1=597660&r2=597661&view=diff
==============================================================================
--- db/derby/code/trunk/java/demo/demo.html (original)
+++ db/derby/code/trunk/java/demo/demo.html Fri Nov 23 05:32:04 2007
@@ -23,14 +23,20 @@
 <BODY>
 
 <H1>Example Apache Derby Programs</H1>
-<p>This directory contains example programs. For a complete description, 
+<p>In this distribution of Apache Derby, the directory
+<em class="fileName">demo/programs/</em> contains example databases and programs
+written in Java. Some of the sample programs are used as references in some of
+the Derby user manuals,
 see <A href="../../docs/html/getstart/index.html">Getting Started with Apache Derby</A>
and 
-the <A href="../../docs/html/adminguide/index.html">Apache Derby Server and Administration
Guide</A> 
-.</p>
+the <A href="../../docs/html/adminguide/index.html">Apache Derby Server and Administration
Guide</A>.
+Other programs are simply demonstrations of how to get started using Derby,
+or how to utilize certain features.</p>
 <UL>
 <LI><A href="simple/example.html">Simple</A>
         <p class="BodyRelative">A very simple JDBC application that boots the driver,
-                                creates a database, and loads some data.</p></LI>
+        creates a database, and loads some data. This application can run in both
+        embedded and client/server settings.</p>
+</LI>
 <li><a href="simplemobile/readme.html">Simple Mobile Demo</a>
     <p class="BodyRelative">A simple JDBC application for Java ME (J2ME) environments.
     This demo application uses Derby's EmbeddedSimpleDataSource to create a database and

Added: db/derby/code/trunk/java/demo/derbylogo128_bluebg.png
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/derbylogo128_bluebg.png?rev=597661&view=auto
==============================================================================
Binary file - no diff available.

Propchange: db/derby/code/trunk/java/demo/derbylogo128_bluebg.png
------------------------------------------------------------------------------
    svn:mime-type = image/png

Modified: db/derby/code/trunk/java/demo/navbar.html
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/navbar.html?rev=597661&r1=597660&r2=597661&view=diff
==============================================================================
--- db/derby/code/trunk/java/demo/navbar.html (original)
+++ db/derby/code/trunk/java/demo/navbar.html Fri Nov 23 05:32:04 2007
@@ -23,13 +23,16 @@
 </HEAD>
 <BODY class="SmallFile">
 
-<p class="NavBar"><a href="demo.html" target="mainPage">Demo home</a></li></p>
-<p class="NavBar1"><a href="simple/example.html" target="mainPage">Simple</a></p>
-<p class="NavBar1"><a href="simplemobile/readme.html" target="mainPage">Simple
Mobile Demo</a></p>
-<p class="NavBar1"><a href="nserverdemo/readme.html" target="mainPage">Network
Server Sample Programs</a></p>
-<p class="NavBar1"><a href="toursdb/toursdb_readme.html" target="mainPage">ToursDB
sample database schema</a></p>
-<p class="NavBar1"><a href="workingwithderby/readme.html" target="mainPage">Getting
Started With Derby Activities Programs</a></p>
-<p class="NavBar"><a href="http://db.apache.org/derby/manuals/index.html" target="_top">Documentation
Home</a></p>
+<a href="../../index.html" target="_top"><img src="derbylogo128_bluebg.png" width="128"
height="100" alt="Derby installation home page (Derby hat logo)"></a>
+<p class="NavBar"><a href="demo.html" target="mainPage">Demo home</a></p>
+<div class="navMenu">
+  <p class="NavBar1"><a href="simple/example.html" target="mainPage">Simple</a></p>
+  <p class="NavBar1"><a href="simplemobile/readme.html" target="mainPage">Simple
Mobile Demo</a></p>
+  <p class="NavBar1"><a href="nserverdemo/readme.html" target="mainPage">Network
Server Sample Programs</a></p>
+  <p class="NavBar1"><a href="toursdb/toursdb_readme.html" target="mainPage">ToursDB
sample database schema</a></p>
+  <p class="NavBar1"><a href="workingwithderby/readme.html" target="mainPage">Getting
Started With Derby Activities Programs</a></p>
+</div>
+<p class="NavBar"><a href="http://db.apache.org/derby/manuals/index.html" target="_top">Online
Documentation</a></p>
 
 </BODY>
 </HTML>

Modified: db/derby/code/trunk/java/demo/readme.html
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/readme.html?rev=597661&r1=597660&r2=597661&view=diff
==============================================================================
--- db/derby/code/trunk/java/demo/readme.html (original)
+++ db/derby/code/trunk/java/demo/readme.html Fri Nov 23 05:32:04 2007
@@ -14,18 +14,15 @@
   See the License for the specific language governing permissions and
   limitations under the License.
 -->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
 
 <html>
-<head><META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<head>
+    <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+    <title>Apache Derby demos</title>
 </head>
 <frameset cols="170, *">
-    <frame src="navbar.html" name="navbar" scrolling="Auto" noresize>	   
-    <frame src="demo.html" name="mainPage" scrolling="Auto">
+    <frame src="navbar.html" name="navbar" scrolling="Auto" noresize frameborder="0">
+    <frame src="demo.html" name="mainPage" scrolling="Auto" frameborder="0">
 </frameset>
-<body>
-
-
-
-</body>
 </html>

Modified: db/derby/code/trunk/java/demo/simple/SimpleApp.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/demo/simple/SimpleApp.java?rev=597661&r1=597660&r2=597661&view=diff
==============================================================================
--- db/derby/code/trunk/java/demo/simple/SimpleApp.java (original)
+++ db/derby/code/trunk/java/demo/simple/SimpleApp.java Fri Nov 23 05:32:04 2007
@@ -21,226 +21,471 @@
 
 import java.sql.Connection;
 import java.sql.DriverManager;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 
+import java.util.ArrayList;
 import java.util.Properties;
 
 
 /**
- * This sample program is a minimal JDBC application showing
- * JDBC access to Derby.
- *
+ * <p>
+ * This sample program is a minimal Java application showing JDBC access to a
+ * Derby database.</p>
+ * <p>
  * Instructions for how to run this program are
- * given in <A HREF=example.html>example.html</A>.
- *
+ * given in <A HREF=example.html>example.html</A>, by default located in the
+ * same directory as this source file ($DERBY_HOME/demo/programs/simple/).</p>
+ * <p>
  * Derby applications can run against Derby running in an embedded
- * or a client/server framework. When Derby runs in an embedded framework,
- * the Derby application and Derby run in the same JVM. The application
- * starts up the Derby engine. When Derby runs in a client/server framework,
- * the application runs in a different JVM from Derby. The application only needs
- * to start the client driver, and the connectivity framework provides network connections.
- * (The server must already be running.)
- *
- * <p>When you run this application, give one of the following arguments:
- *    * embedded (default, if none specified)
- *    * derbyclient (will use the Net client driver to access Network Server)
- *    * jccjdbcclient (if Derby is running embedded in the JCC Server framework)
- *
+ * or a client/server framework.</p>
+ * <p>
+ * When Derby runs in an embedded framework, the JDBC application and Derby
+ * run in the same Java Virtual Machine (JVM). The application
+ * starts up the Derby engine.</p>
+ * <p>
+ * When Derby runs in a client/server framework, the application runs in a
+ * different JVM from Derby. The application only needs to load the client
+ * driver, and the connectivity framework (in this case the Derby Network
+ * Server) provides network connections.</p>
  */
 public class SimpleApp
 {
     /* the default framework is embedded*/
-    public String framework = "embedded";
-    public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
-    public String protocol = "jdbc:derby:";
-
+    private String framework = "embedded";
+    private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
+    private String protocol = "jdbc:derby:";
+
+    /**
+     * <p>
+     * Starts the demo by creating a new instance of this class and running
+     * the <code>go()</code> method.</p>
+     * <p>
+     * When you run this application, you may give one of the following
+     * arguments:
+     *  <ul>
+          <li><code>embedded</code> - default, if none specified. Will
use
+     *        Derby's embedded driver. This driver is included in the derby.jar
+     *        file.</li>
+     *    <li><code>derbyclient</code> - will use the Derby client driver
to
+     *        access the Derby Network Server. This driver is included in the
+     *        derbyclient.jar file.</li>
+     *    <li><code>jccjdbcclient</code> - will use the DB2 Universal JDBC
+     *        network client driver, also known as JCC, to access the Network
+     *        Server. This driver is not part of the Derby distribution.</li>
+     *  </ul>
+     * <p>
+     * When you are using a client/server framework, the network server must
+     * already be running when trying to obtain client connections to Derby.
+     * This demo program will will try to connect to a network server on this
+     * host (the localhost), see the <code>protocol</code> instance variable.
+     * </p>
+     * <p>
+     * When running this demo, you must include the correct driver in the
+     * classpath of the JVM. See <a href="example.html">example.html</a> for
+     * details.
+     * </p>
+     * @param args This program accepts one optional argument specifying which
+     *        connection framework (JDBC driver) to use (see above). The default
+     *        is to use the embedded JDBC driver.
+     */
     public static void main(String[] args)
     {
         new SimpleApp().go(args);
+        System.out.println("SimpleApp finished");
     }
 
+    /**
+     * <p>
+     * Starts the actual demo activities. This includes loading the correct
+     * JDBC driver, creating a database by making a connection to Derby,
+     * creating a table in the database, and inserting, updating and retreiving
+     * some data. Some of the retreived data is then verified (compared) against
+     * the expected results. Finally, the table is deleted and, if the embedded
+     * framework is used, the database is shut down.</p>
+     * <p>
+     * Generally, when using a client/server framework, other clients may be
+     * (or want to be) connected to the database, so you should be careful about
+     * doing shutdown unless you know that noone else needs to access the
+     * database until it is rebooted. That is why this demo will not shut down
+     * the database unless it is running Derby embedded.</p>
+     *
+     * @param args - Optional argument specifying which framework or JDBC driver
+     *        to use to connect to Derby. Default is the embedded framework,
+     *        see the <code>main()</code> method for details.
+     * @see #main(String[])
+     */
     void go(String[] args)
     {
         /* parse the arguments to determine which framework is desired*/
         parseArguments(args);
 
-        System.out.println("SimpleApp starting in " + framework + " mode.");
+        System.out.println("SimpleApp starting in " + framework + " mode");
+
+        /* load the desired JDBC driver */
+        loadDriver();
 
+        /* We will be using Statement and PreparedStatement objects for
+         * executing SQL. These objects, as well as Connections and ResultSets,
+         * are resources that should be released explicitly after use, hence
+         * the try-catch-finally pattern used below.
+         * We are storing the Statement and Prepared statement object references
+         * in an array list for convenience.
+         */
+        Connection conn = null;
+	/* This ArrayList usage may cause a warning when compiling this class
+	 * with a compiler for J2SE 5.0 or newer. We are not using generics
+	 * because we want the source to support J2SE 1.4.2 environments. */
+        ArrayList statements = new ArrayList(); // list of Statements, PreparedStatements
+        PreparedStatement psInsert = null;
+        PreparedStatement psUpdate = null;
+        Statement s = null;
+        ResultSet rs = null;
         try
         {
-            /*
-               The driver is installed by loading its class.
-               In an embedded environment, this will start up Derby, since it is not already
running.
-             */
-            Class.forName(driver).newInstance();
-            System.out.println("Loaded the appropriate driver.");
-
-            Connection conn = null;
-            Properties props = new Properties();
+            Properties props = new Properties(); // connection properties
+            // providing a user name and password is optional in the embedded
+            // and derbyclient frameworks
             props.put("user", "user1");
             props.put("password", "user1");
 
-            /*
-               The connection specifies create=true to cause
-               the database to be created. To remove the database,
-               remove the directory derbyDB and its contents.
-               The directory derbyDB will be created under
-               the directory that the system property
-               derby.system.home points to, or the current
-               directory if derby.system.home is not set.
+            /* By default, the schema APP will be used when no username is
+             * provided.
+             * Otherwise, the schema name is the same as the user name (in this
+             * case "user1" or USER1.)
+             *
+             * Note that user authentication is off by default, meaning that any
+             * user can connect to your database using any password. To enable
+             * authentication, see the Derby Developer's Guide.
              */
-            conn = DriverManager.getConnection(protocol +
-                    "derbyDB;create=true", props);
-
-            System.out.println("Connected to and created database derbyDB");
 
-            conn.setAutoCommit(false);
+            String dbName = "derbyDB"; // the name of the database
 
             /*
-               Creating a statement lets us issue commands against
-               the connection.
+             * This connection specifies create=true in the connection URL to
+             * cause the database to be created when connecting for the first
+             * time. To remove the database, remove the directory derbyDB (the
+             * same as the database name) and its contents.
+             *
+             * The directory derbyDB will be created under the directory that
+             * the system property derby.system.home points to, or the current
+             * directory (user.dir) if derby.system.home is not set.
              */
-            Statement s = conn.createStatement();
+            conn = DriverManager.getConnection(protocol + dbName
+                    + ";create=true", props);
 
-            /*
-               We create a table, add a few rows, and update one.
+            System.out.println("Connected to and created database " + dbName);
+
+            // We want to control transactions manually. Autocommit is on by
+            // default in JDBC.
+            conn.setAutoCommit(false);
+
+            /* Creating a statement object that we can use for running various
+             * SQL statements commands against the database.*/
+            s = conn.createStatement();
+            statements.add(s);
+
+            // We create a table...
+            s.execute("create table location(num int, addr varchar(40))");
+            System.out.println("Created table location");
+
+            // and add a few rows...
+
+            /* It is recommended to use PreparedStatements when you are
+             * repeating execution of an SQL statement. PreparedStatements also
+             * allows you to parameterize variables. By using PreparedStatements
+             * you may increase performance (because the Derby engine does not
+             * have to recompile the SQL statement each time it is executed) and
+             * improve security (because of Java type checking).
              */
-            s.execute("create table derbyDB(num int, addr varchar(40))");
-            System.out.println("Created table derbyDB");
-            s.execute("insert into derbyDB values (1956,'Webster St.')");
+            // parameter 1 is num (int), parameter 2 is addr (varchar)
+            psInsert = conn.prepareStatement(
+                        "insert into location values (?, ?)");
+            statements.add(psInsert);
+
+            psInsert.setInt(1, 1956);
+            psInsert.setString(2, "Webster St.");
+            psInsert.executeUpdate();
             System.out.println("Inserted 1956 Webster");
-            s.execute("insert into derbyDB values (1910,'Union St.')");
+
+            psInsert.setInt(1, 1910);
+            psInsert.setString(2, "Union St.");
+            psInsert.executeUpdate();
             System.out.println("Inserted 1910 Union");
-            s.execute(
-                "update derbyDB set num=180, addr='Grand Ave.' where num=1956");
+
+            // Let's update some rows as well...
+
+            // parameter 1 and 3 are num (int), parameter 2 is addr (varchar)
+            psUpdate = conn.prepareStatement(
+                        "update location set num=?, addr=? where num=?");
+            statements.add(psUpdate);
+
+            psUpdate.setInt(1, 180);
+            psUpdate.setString(2, "Grand Ave.");
+            psUpdate.setInt(3, 1956);
+            psUpdate.executeUpdate();
             System.out.println("Updated 1956 Webster to 180 Grand");
 
-            s.execute(
-                "update derbyDB set num=300, addr='Lakeshore Ave.' where num=180");
+            psUpdate.setInt(1, 300);
+            psUpdate.setString(2, "Lakeshore Ave.");
+            psUpdate.setInt(3, 180);
+            psUpdate.executeUpdate();
             System.out.println("Updated 180 Grand to 300 Lakeshore");
 
+
             /*
                We select the rows and verify the results.
              */
-            ResultSet rs = s.executeQuery(
-                    "SELECT num, addr FROM derbyDB ORDER BY num");
+            rs = s.executeQuery(
+                    "SELECT num, addr FROM location ORDER BY num");
 
+            /* we expect the first returned column to be an integer (num),
+             * and second to be a String (addr). Rows are sorted by street
+             * number (num).
+             *
+             * Normally, it is best to use a pattern of
+             *  while(rs.next()) {
+             *    // do something with the result set
+             *  }
+             * to process all returned rows, but we are only expecting two rows
+             * this time, and want the verification code to be easy to
+             * comprehend, so we use a different pattern.
+             */
+
+            int number; // street number retreived from the database
+            boolean failure = false;
             if (!rs.next())
             {
-                throw new Exception("Wrong number of rows");
+                failure = true;
+                reportFailure("No rows in ResultSet");
             }
 
-            if (rs.getInt(1) != 300)
+            if ((number = rs.getInt(1)) != 300)
             {
-                throw new Exception("Wrong row returned");
+                failure = true;
+                reportFailure(
+                        "Wrong row returned, expected num=300, got " + number);
             }
 
             if (!rs.next())
             {
-                throw new Exception("Wrong number of rows");
+                failure = true;
+                reportFailure("Too few rows");
             }
 
-            if (rs.getInt(1) != 1910)
+            if ((number = rs.getInt(1)) != 1910)
             {
-                throw new Exception("Wrong row returned");
+                failure = true;
+                reportFailure(
+                        "Wrong row returned, expected num=1910, got " + number);
             }
 
             if (rs.next())
             {
-                throw new Exception("Wrong number of rows");
+                failure = true;
+                reportFailure("Too many rows");
             }
 
-            System.out.println("Verified the rows");
+            if (!failure) {
+                System.out.println("Verified the rows");
+            }
 
-            s.execute("drop table derbyDB");
-            System.out.println("Dropped table derbyDB");
+            // delete the table
+            s.execute("drop table location");
+            System.out.println("Dropped table location");
 
             /*
-               We release the result and statement resources.
-             */
-            rs.close();
-            s.close();
-            System.out.println("Closed result set and statement");
-
-            /*
-               We end the transaction and the connection.
+               We commit the transaction. Any changes will be persisted to
+               the database now.
              */
             conn.commit();
-            conn.close();
-            System.out.println("Committed transaction and closed connection");
+            System.out.println("Committed the transaction");
 
             /*
-               In embedded mode, an application should shut down Derby.
-               If the application fails to shut down Derby explicitly,
-               the Derby does not perform a checkpoint when the JVM shuts down, which means
-               that the next connection will be slower.
-               Explicitly shutting down Derby with the URL is preferred.
-               This style of shutdown will always throw an "exception".
+             * In embedded mode, an application should shut down the database.
+             * If the application fails to shut down the database,
+             * Derby will not perform a checkpoint when the JVM shuts down.
+             * This means that it will take longer to boot (connect to) the
+             * database the next time, because Derby needs to perform a recovery
+             * operation.
+             *
+             * It is also possible to shut down the Derby system/engine, which
+             * automatically shuts down all booted databases.
+             *
+             * Explicitly shutting down the database or the Derby engine with
+             * the connection URL is preferred. This style of shutdown will
+             * always throw an SQLException.
+             *
+             * Not shutting down when in a client environment, see method
+             * Javadoc.
              */
-            boolean gotSQLExc = false;
 
             if (framework.equals("embedded"))
             {
                 try
                 {
+                    // the shutdown=true attribute shuts down Derby
                     DriverManager.getConnection("jdbc:derby:;shutdown=true");
-                }
-                catch (SQLException se)
-                {
-                    gotSQLExc = true;
-                }
 
-                if (!gotSQLExc)
-                {
-                    System.out.println("Database did not shut down normally");
+                    // To shut down a specific database only, but keeep the
+                    // engine running (for example for connecting to other
+                    // databases), specify a database in the connection URL:
+                    //DriverManager.getConnection("jdbc:derby:" + dbName + ";shutdown=true");
                 }
-                else
+                catch (SQLException se)
                 {
-                    System.out.println("Database shut down normally");
+                    if (( (se.getErrorCode() == 50000)
+                            && ("XJ015".equals(se.getSQLState()) ))) {
+                        // we got the expected exception
+                        System.out.println("Derby shut down normally");
+                        // Note that for single database shutdown, the expected
+                        // SQL state is "08006", and the error code is 45000.
+                    } else {
+                        // if the error code or SQLState is different, we have
+                        // an unexpected exception (shutdown failed)
+                        System.err.println("Derby did not shut down normally");
+                        printSQLException(se);
+                    }
                 }
             }
         }
-        catch (Throwable e)
+        catch (SQLException sqle)
         {
-            System.out.println("exception thrown:");
+            printSQLException(sqle);
+        } finally {
+            // release all open resources to avoid unnecessary memory usage
+
+            // ResultSet
+            try {
+                if (rs != null) {
+                    rs.close();
+                    rs = null;
+                }
+            } catch (SQLException sqle) {
+                printSQLException(sqle);
+            }
 
-            if (e instanceof SQLException)
-            {
-                printSQLError((SQLException) e);
+            // Statements and PreparedStatements
+            int i = 0;
+            while (!statements.isEmpty()) {
+                // PreparedStatement extend Statement
+                Statement st = (Statement)statements.remove(i);
+                try {
+                    if (st != null) {
+                        st.close();
+                        st = null;
+                    }
+                } catch (SQLException sqle) {
+                    printSQLException(sqle);
+                }
             }
-            else
-            {
-                e.printStackTrace();
+
+            //Connection
+            try {
+                if (conn != null) {
+                    conn.close();
+                    conn = null;
+                }
+            } catch (SQLException sqle) {
+                printSQLException(sqle);
             }
         }
+    }
 
-        System.out.println("SimpleApp finished");
+    /**
+     * Loads the appropriate JDBC driver for this environment/framework. For
+     * example, if we are in an embedded environment, we load Derby's
+     * embedded Driver, <code>org.apache.derby.jdbc.EmbeddedDriver</code>.
+     */
+    private void loadDriver() {
+        /*
+         *  The JDBC driver is loaded by loading its class.
+         *  If you are using JDBC 4.0 (Java SE 6) or newer, JDBC drivers may
+         *  be automatically loaded, making this code optional.
+         *
+         *  In an embedded environment, this will also start up the Derby
+         *  engine (though not any databases), since it is not already
+         *  running. In a client environment, the Derby engine is being run
+         *  by the network server framework.
+         *
+         *  In an embedded environment, any static Derby system properties
+         *  must be set before loading the driver to take effect.
+         */
+        try {
+            Class.forName(driver).newInstance();
+            System.out.println("Loaded the appropriate driver");
+        } catch (ClassNotFoundException cnfe) {
+            System.err.println("\nUnable to load the JDBC driver " + driver);
+            System.err.println("Please check your CLASSPATH.");
+            cnfe.printStackTrace(System.err);
+        } catch (InstantiationException ie) {
+            System.err.println(
+                        "\nUnable to instantiate the JDBC driver " + driver);
+            ie.printStackTrace(System.err);
+        } catch (IllegalAccessException iae) {
+            System.err.println(
+                        "\nNot allowed to access the JDBC driver " + driver);
+            iae.printStackTrace(System.err);
+        }
+    }
+
+    /**
+     * Reports a data verification failure to System.err with the given message.
+     *
+     * @param message A message describing what failed.
+     */
+    private void reportFailure(String message) {
+        System.err.println("\nData verification failed:");
+        System.err.println('\t' + message);
     }
 
-    static void printSQLError(SQLException e)
+    /**
+     * Prints details of an SQLException chain to <code>System.err</code>.
+     * Details included are SQL State, Error code, Exception message.
+     *
+     * @param e the SQLException from which to print details.
+     */
+    public static void printSQLException(SQLException e)
     {
+        // Unwraps the entire exception chain to unveil the real cause of the
+        // Exception.
         while (e != null)
         {
-            System.out.println(e.toString());
+            System.err.println("\n----- SQLException -----");
+            System.err.println("  SQL State:  " + e.getSQLState());
+            System.err.println("  Error Code: " + e.getErrorCode());
+            System.err.println("  Message:    " + e.getMessage());
+            // for stack traces, refer to derby.log or uncomment this:
+            //e.printStackTrace(System.err);
             e = e.getNextException();
         }
     }
 
+    /**
+     * Parses the arguments given and sets the values of this class' instance
+     * variables accordingly - that is which framework to use, the name of the
+     * JDBC driver class, and which connection protocol protocol to use. The
+     * protocol should be used as part of the JDBC URL when connecting to Derby.
+     * <p>
+     * If the argument is "embedded" or invalid, this method will not change
+     * anything, meaning that the default values will be used.</p>
+     * <p>
+     * @param args JDBC connection framework, either "embedded", "derbyclient"
+     *        or "jccjdbcclient". Only the first argument will be considered,
+     *        the rest will be ignored.
+     */
     private void parseArguments(String[] args)
     {
-        int length = args.length;
-
-        for (int index = 0; index < length; index++)
-        {
-            if (args[index].equalsIgnoreCase("jccjdbcclient"))
+        if (args.length > 0) {
+            if (args[0].equalsIgnoreCase("jccjdbcclient"))
             {
                 framework = "jccjdbc";
                 driver = "com.ibm.db2.jcc.DB2Driver";
                 protocol = "jdbc:derby:net://localhost:1527/";
             }
-            if (args[index].equalsIgnoreCase("derbyclient"))
+            else if (args[0].equalsIgnoreCase("derbyclient"))
             {
                 framework = "derbyclient";
                 driver = "org.apache.derby.jdbc.ClientDriver";



Mime
View raw message