Get Start Derby
Get Start Derby
Get Start Derby
Version 10.5
Contents
Copyright................................................................................................................................3 License................................................................................................................................... 4 Relationship between Java DB and Derby.........................................................................8 Introduction to Derby........................................................................................................... 9 Deployment options...................................................................................................9 System requirements.................................................................................................9 Product documentation for Java DB....................................................................... 9 Installing and configuring Derby.......................................................................................11 Installing Java DB....................................................................................................11 Setting up your environment..................................................................................11 Choosing a method to run the Derby tools and startup utilities...........................11 Setting the environment variables.......................................................................12 Syntax for the derbyrun.jar file............................................................................ 13 Manually setting the CLASSPATH environment variable....................................14 Using the Derby tools and startup utilities........................................................... 14 Running sysinfo................................................................................................... 15 Running ij.............................................................................................................16 Running dblook....................................................................................................17 Verifying the Derby system configuration............................................................ 18 Self-study tutorial for users new to Derby.......................................................................20 Tutorial overview......................................................................................................20 Activity 1: Run SQL using the embedded driver..................................................21 Creating a directory and copying scripts into the directory................................. 21 Creating a Derby database and running SQL statements.................................. 22 Activity 2: Run SQL using the client driver.......................................................... 24 Activity 3: Run a JDBC program using the embedded driver............................. 26 The WwdEmbedded program............................................................................. 27 Activity 4: Create and run a JDBC program using the client driver and Network Server........................................................................................................................ 30 What next with Derby?............................................................................................33 Quick start guide for experienced JDBC users............................................................... 35 Environments in which Derby can run..................................................................35 Embedded environment...................................................................................... 35 Client/server environment....................................................................................35 Available drivers...................................................................................................... 35 Database connection URL...................................................................................... 35 Documentation conventions.............................................................................................. 37 Terminology.............................................................................................................. 37 SQL syntax............................................................................................................... 37 Typographical conventions.................................................................................... 37 Derby libraries and scripts: complete reference ............................................................ 39 Libraries provided by Derby...................................................................................39 Scripts included with Derby................................................................................... 40 Trademarks.......................................................................................................................... 41
Copyright
Copyright 2004-2009 The Apache Software Foundation Copyright 2009 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Related information License
License
The Apache License, Version 2.0
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems
that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form that You distribute, all copyright, attribution notices from the Source excluding those notices that do not the Derivative Works; and of any Derivative Works patent, trademark, and form of the Work, pertain to any part of
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications
and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
(TM)
DB and Derby
Java DB is a relational database management system that is based on the Java programming language and SQL. Java DB is a commercial release of the Apache Software Foundation's (ASF) open source relational database project. The Apache project is called Derby. The Java DB product includes Derby without any modification whatsoever to the underlying source code. Technical support is available for purchase for the Java DB product through Sun. Because Java DB and Derby have the same functionality, the Java DB documentation refers to the core functionality as Derby. Java DB Version 10.5 is based on the Derby Version 10.5 release. References to "Derby" in the Java DB documentation refer to the Version 10.5 release of Apache Derby.
Introduction to Derby
Welcome to Derby! Derby is a full-featured, open source relational database management system (RDBMS) that is based on Java
(TM)
and SQL.
Derby is written and implemented completely in the Java programming language. Derby provides users with a small-footprint standards-based database engine that can be tightly embedded into any Java based solution. Derby ensures data integrity and provides sophisticated transaction support. In the default configuration there is no separate database server to be installed or maintained by the end user. For more information on Derby, visit the Derby Web site at http://db.apache.org/derby. Before you install Derby, you should understand the deployment options and system requirements.
Deployment options
The Derby software distribution provides two basic deployment options (also referred to as frameworks), the simple embedded option and the Derby Network Server option. Embedded Refers to Derby being started by a simple single-user Java application. With this option Derby runs in the same Java virtual machine (JVM) as the application. Derby can be almost invisible to the end user because it is started and stopped by the application and often requires no administration. The Derby documentation often refers to this as the embedded configuration or embedded mode. Server (or Server-based) Refers to Derby being started by an application that provides multi-user connectivity to Derby databases across a network. With this option Derby runs in the Java virtual machine (JVM) that hosts the Server. Applications connect to the Server from different JVMs to access the database. The Derby Network Server is part of the Derby software distribution and provides this type of framework for Derby. Derby also works well with other, independently developed Server applications. The Derby documentation often refers to this as the Network Server configuration or client/server configuration.
System requirements
Derby is a database engine written completely in Java. The database will run in any certified Java Virtual Machine (JVM). You must have a JAVA version 1.4 or higher installed on your computer. The Java Development Kit (JDK) is required to perform the activities in the Self-study tutorial for users new to Derby. To check that the correct version of Java is installed, issue the java -version command.
Getting Started with Java DB Describes how to install and configure Java DB. Includes a self-study tutorial for users new to Java DB and a quick-start guide for experienced JDBC users. This guide introduces the dblook, ij, and sysinfo tools, and the libraries and scripts that are included with Java DB. Java DB Developer's Guide Describes the functionality and features of Java DB common to all deployments, such as Java DB's JDBC and SQL specifics, deploying Java DB applications, working with properties, security, and other advanced features. Java DB Reference Manual Documents the implementation of the SQL language in Java DB. This guide provides reference information about the JDBC and JTA implementations, keywords, system tables, properties, and SQLExceptions in Java DB. Tuning Java DB This guide offers performance tips, an in-depth discussion of performance, and information about the Java DB optimizer. Java DB Tools and Utilities Guide Describes how to use the the Java DB tools such as dblook, ij, andsysinfo, and how to use the system procedures to import and export data, and how to store Java code in the database. Java DB Server and Administration Guide Part One of this guide discusses configuring servers, how to program client applications, and database administration. In addition, some systems might require administrative tasks such as backing up databases. These tasks are independent of any server framework but are unique to multi-user or large systems. Part Two of this guide discusses administrative issues such as backups and debugging deadlocks. Java DB API Reference An API Reference that is automatically generated for all public Java DB classes. No reference is provided for the JDBC API, which is part of the Java 2 Platform, Standard Edition. For more information about the classes in the API, see the Java DB Reference Manual. You can access the Java DB manuals and API Reference from the Java DB Documentation page on the Java DB web site. The product documentation is also installed with Java DB. The manuals are installed in the docs subdirectory and the API Reference is installed in the javadoc subdirectory.
10
Installing Java DB
To install Java DB you must first download a Java DB install file from the Java DB Web site. Navigate your Web browser to http://developers.sun.com/javadb/downloads/. Click Get It. Follow the instructions on subsequent pages. Extract the downloaded package, which contains the distribution of Java DB. This distribution contains scripts, libraries, and demonstration programs. The extracted installation contains several subdirectories: The bin subdirectory contains the scripts for executing utilities and setting up the environment. The demo subdirectory contains the demonstration programs. The docs subdirectory contains the Java DB documentation. The javadoc subdirectory contains the api documentation that was generated from source code comments. The lib subdirectory contains the Java DB .jar files.
When to Use
Use this method when you want to run the tools with the least amount of typing and have installed the full bin distribution of Derby.
Requirements
Set the DERBY_HOME environment variable Include the java.exe file in the PATH environment variable
11
Include the DERBY_HOME\bin directory in the PATH environment variable Run the tools using the derbyrun.jar archive file. Use this method when: You have only the Derby jar files available (see Libraries provided by Derby), and do not have the full bin distribution of Derby You do not want to use the scripts that are provided with Derby Use this method when: You do not have the derbyrun.jar file or the Derby scripts installed. You want to learn the full syntax of each command and understand the details of setting up the execution environment. You are developing application programs with Derby Set the DERBY_HOME environment variable Include the java.exe file in the PATH environment variable
The derbyrun.jar file must be in the same folder as the other Derby .jar files. For more information see the syntax for the derbyrun.jar file.
Set the DERBY_HOME environment variable Include the java.exefile in the PATH environment variable You must know the full package name for the Java class that supports the tool The CLASSPATH environment variable must be set to include the required JAR files.
Run the tools using the complete java syntax or use Derby in a Java program.
For details on setting the CLASSPATH, see Manually setting the CLASSPATH environment variable.
2. Based on the requirements of the method that you chose to run the tools, follow the instructions to set the environment variables.
12
For example, if you installed Derby in the /opt/Derby_10 directory on UNIX or in the c:\Derby_10 directory on Windows, use the following command to set the DERBY_HOME environment variable: Operating System
UNIX Windows
Command
export DERBY_HOME=/opt/Derby_10 set DERBY_HOME=c:\Derby_10
2. Be certain that the java.exe file, version 1.4.2 or, higher is in your command execution PATH. Open a command window and run the java -version command. 3. Add the DERBY_HOME/bin directory to the PATH environment variable so that you can run the Derby scripts from any directory. Operating System
UNIX Windows
Command
export PATH="$DERBY_HOME/bin:$PATH" set PATH=%DERBY_HOME%\bin;%PATH%. If you use the Control Panel to update your system PATH, add %DERBY_HOME%\bin to the end of the PATH environment variable
Tip: When the DERBY_HOME environment variable is set and the underlying /bin directory is included in the PATH environment variable, you can use shortened commands to start the Derby tools. Otherwise, either you must be in the directory where the script that starts the Derby tool is located, or you must specify the full path to the location of the script when you want to start the tool. For more information on the scripts included in the bin distribution, see Scripts included with Derby.
Command
java -jar $DERBY_HOME/lib/derbyrun.jar ij [-p propertiesfile] [sql_script] java -jar $DERBY_HOME/lib/derbyrun.jar sysinfo [-cp ...] [-cp help] java (or java (or -jar $DERBY_HOME/lib/derbyrun.jar dblook [arg]* no arguments for usage) -jar $DERBY_HOME/lib/derbyrun.jar server [arg]* no arguments for usage)
Windows
13
java -jar %DERBY_HOME%\lib\derbyrun.jar sysinfo [-cp ...] [-cp help] java -jar %DERBY_HOME%\lib\derbyrun.jar dblook [arg]* (or no arguments for usage) java -jar %DERBY_HOME%\lib\derbyrun.jar server [arg]* (or no arguments for usage)
To see this syntax reminder, run the command java -jar derbyrun.jar with no arguments. Additional information The server argument is a shortcut for running the NetworkServerControl tool. For details on using this tool, see the Java DB Server and Administration Guide. For more information on using derbyrun.jar to run the ij, sysinfo, and dblook tools, see the Java DB Tools and Utilities Guide.
There are several tools and utilities that you might want to use as you begin to work with Derby. The tools that are included with Derby are dblook, ij, and sysinfo. To run these tools see: Running sysinfo Running ij Running dblook Derby includes a set of scripts that you can use to start the Derby tools. The scripts are located in the DERBY_HOME/bin directory. When you run these scripts, your CLASSPATH environment variable is set if you have not already set it, and remains set as long as you are running the tool. Most of the examples in this guide that show how to use the Derby scripts to launch the Derby tools assume that you are using the embedded mode of the Derby database engine. Use the instructions below to run the scripts with the Network Server. Running the scripts with the Network Server To run the scripts with the Network Server, use the following commands: For the sysinfo tool, issue the command
NetworkServerControl sysinfo
and then start ij by issuing the command ij. For the dblook tool, call the script and specify the -d option and the full connection URL to the Network Server database. For example:
dblook -d 'jdbc:derby://localhost/myDB;user=usr'
Additional Derby utilities In addition, there are Derby utilities that are system procedures that you can call by using the ij tool. For example, there are system procedures that you can use to import and export external files. Instructions on how to use these system procedures are included in the Java DB Tools and Utilities Guide and the Java DB Reference Manual.
Running sysinfo
The Derby sysinfo tool displays information about your Java environment and your version of Derby. The sysinfo utility prints system information to a console. Choose the method that you can use to run the sysinfo script: Method
Run sysinfo as a standalone command.
When to Use
Use this method if you are relatively new to the Java programming language and new to Derby.
Command
You must set your environment variables before you can run the sysinfo utility using this method.
15
The sysinfo script sets the appropriate environment variables, including the CLASSPATH, and runs the sysinfo utility.
Run sysinfo using the jar file that is located in the directory where sysinfo resides. Use this method if you are new to Derby, but are familiar with the Java programming language. You must set the DERBY_HOME environment variable before you can run the sysinfo utility using this method.
See "sysinfo" in the Java DB Tools and Utilities Guide for more information about using the sysinfo utility.
Running ij
The Derby ij tool is a JDBC tool that you can use to run scripts or interactive queries against a Derby database. Choose the method that you can use to run the ij script: Method
Run ij as a standalone command.
When to Use
Use this method if you are relatively new to the Java programming language and new to Derby.
Command
You must set your environment variables before you can run the ij tool using this method. To run the ij script from the command line use: ij
You must add the DERBY_HOME/bin directory in your PATH environment variable before you can run the ij tool. The ij script sets up the environment variables like CLASSPATH and starts the ij tool.
Run ij using the jar file that is located in the directory where ij resides. Use this method if you are new to Derby, but are familiar with the You must set the DERBY_HOME environment variable before you can run the ij tool using this method.
16
See the Java DB Tools and Utilities Guide for more information about the ij tool.
Running dblook
The Derby dblook utility is a Data Definition Language (DDL) generation utility. The dblook utility is a simple utility that dumps all or parts of the DDL of a user-specified database to either a console or a file. The generated DDL can then be used for such things as recreating all or parts of a database, viewing a subset of the objects in a database (for example, those objects that pertain to specific tables and schemas), or documenting the schema of a database. Choose the method that you can use to run the dblook script: Method
Run dblook as a standalone command.
When to Use
Use this method if you are relatively new to the Java programming language and new to Derby.
Command
You must set your environment variables before you can run the dblook utility using this method.
The dblook script sets the appropriate environment variables, including the CLASSPATH, and runs the dblook utility.
Run dblook using the jar file that is located in the directory where dblook resides. Use this method if you are new to Derby, but are familiar with the Java programming language. You must set the DERBY_HOME environment variable before you can run the dblook utility using this method.
17
See Using the Derby tools and startup utilities for an example of the use of the connectionURL. See "dblook" and its subtopics in the Java DB Tools and Utilities Guide for more information about using the dblook utility.
The output you see might be different from what is shown here because the java -version command outputs vendor-specific information. If the command produces an error or the version listed is not 1.4 or higher, install a JDK before continuing. 2. Verify that the DERBY_HOME environment variable is set and points to the root directory of the Derby 10.5 installation. Open a command window and run the appropriate command for your system. If you installed Derby in the /opt/Derby_10 directory on UNIX or the c:\Derby_10 directory on Windows, the command that you use and the expected output are shown in the following table: Operating System UNIX (Korn Shell) Windows Command echo $DERBY_HOME echo %DERBY_HOME% Output /opt/Derby_10 C:\Derby_10
If you receive an error or do not see the expected output, ensure that you have set the DERBY_HOME environment variable, as described in Setting the environment variables. Note: You can also use the sysinfo utility to verify that the environment variables are set correctly. If the environment variables are set correctly, the sysinfo command 18
displays information about your Java virtual machine (JVM) and the version of Derby that you have installed.
19
Tutorial overview
Each activity in this self-study tutorial highlights an important feature of Derby. Here is what you can expect to learn in each activity: Activity 1: Use the Derby ij tool to load the Derby embedded driver and start the Derby database engine. Create the database firstdb and the table FIRSTTABLE. Use a few basic SQL statements to insert and select data. The Derby message log derby.log and the database directories and files are introduced. Activity 2: Use Derby within a client/server configuration. Start the Derby Network Server, which will embed the Derby engine. In a separate process, use the Derby ij tool to load the Derby client driver and connect to the Network Server. Create a database called seconddb and the table SECONDTABLE. Use a few basic SQL statements to insert and select data. Activity 3: 20
Load the Derby database engine from a simple Java JDBC program. Use the embedded driver to create the database jdbcDemoDB and the WISH_LIST table. Populate the table with text entered from the keyboard, then view a list of the records in the table. Walk through the code to understand the basic structure of a JDBC program that accesses a Derby database. The CLASSPATH variable and connection URL attribute ;shutdown=true are introduced. Activity 4: Modify the Java JDBC program to load the client driver and connect to the Derby Network Server. Compile the altered program and test that the program operates as it did in the previous activity.
Command
md DERBYTUTOR
3. Change to the DERBYTUTOR directory. Operating System UNIX (Korn Shell) Windows
cd DERBYTUTOR
Command
cd DERBYTUTOR
4. Copy the SQL scripts from the Derby demo\programs\toursdb subdirectory into the DERBYTUTOR directory. You will use these scripts to create tables and add data to a new database, toursdb. Operating System UNIX Command
cp $DERBY_HOME/demo/programs/toursdb/*.sql .
21
5. Verify that the files were copied to the DERBYTUTOR directory. Operating System UNIX (Korn Shell) Windows
ls DERBYTUTOR
Command
dir DERBYTUTOR
> Important: Include the dot (.) at the end of each command so that your current working directory is included in the classpath and the files are copied to the correct location.
Otherwise, you can use the java command to start the ij tool. Operating System UNIX (Korn Shell) Windows Command
java -jar $DERBY_HOME/lib/derbyrun.jar ij ij version 10.5 java -jar %DERBY_HOME%\lib\derbyrun.jar ij ij version 10.5
2. Create the database and open a connection to the database using the embedded driver.
CONNECT 'jdbc:derby:firstdb;create=true';
Description of connection command: connect The ij command to establish a connection to a database. The Derby connection URL is enclosed in single quotation marks. An ij command can be in either uppercase or lowercase. jdbc:derby: The JDBC protocol specification for the Derby driver. firstdb The name of the database. The name can be any string. Because no filepath is specified, the database is created in the default working directory (DERBYTUTOR). ;create=true The Derby URL attribute that is used to create a database. Derby does not have an SQL create database command. ; 22
The semicolon is the ij command terminator. 3. Create a table with two columns using standard SQL.
CREATE TABLE FIRSTTABLE (ID INT PRIMARY KEY, NAME VARCHAR(12)); 0 rows inserted/updated/deleted
7. Optional: Create and populate additional tables and other schema objects. a. Load the SQL script ToursDB_schema.sql.
run 'ToursDB_schema.sql'; ij> ... CREATE TABLE AIRLINES ( AIRLINE CHAR(2) NOT NULL , AIRLINE_FULL VARCHAR(24), BASIC_RATE DOUBLE PRECISION, ... 0 rows inserted/updated/deleted ... Other output messages not shown ...
You should be returned to the DERBYTUTOR directory. 9. Browse the most important files created by this activity: The derby.log file. This file is a message and error log that, under normal circumstances, contains a set of startup messages and a shutdown message.
23
---------------------------------------------------------------2009-05-08 16:55:29.736 GMT: Booting Derby version The Apache Software Foundation - Apache Derby - 10.5.1.1 - (764942): instance a816c00e-0121-2126-a56a-000000418588 on database directory C:\DERBYTUTOR\firstdb Database Class Loader started - derby.database.classpath='' 2009-05-08 16:56:37.367 GMT: Shutting down instance a816c00e-0121-2126-a56a-000000418588 ----------------------------------------------------------------
The firstdb database directory. Within the directory are the subdirectories seg0 (containing the data files) and log (containing the transaction log files).
Windows
A Network Server startup message appears in the Shell-1 command window. 3. Open another command window (Shell-2). Change to the DERBYTUTOR directory. 4. Start ij. If you included the DERBY_HOME/bin directory in your PATH environment variable, type:
ij
Otherwise, you can use the java command to start the ij tool. Command
24
You will enter all subsequent commands from the network client, so you will type the commands in the Shell-2 command window. 5. Create and open a connection to the database using the client driver.
CONNECT 'jdbc:derby://localhost:1527/seconddb;create=true';
Remember: A client connection URL contains a hostname and a port number. For example: //localhost:1527/ 6. Create a table with two columns (ID and NAME) using the following SQL statement:
CREATE TABLE SECONDTABLE (ID INT PRIMARY KEY, NAME VARCHAR(14)); 0 rows inserted/updated/deleted
11. Shut down the Derby Network Server. Operating System UNIX (Korn Shell) Windows Command
java -jar $DERBY_HOME/lib/derbyrun.jar server shutdown 2009-05-08 17:07:25.887 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) shutdown java -jar %DERBY_HOME%\lib\derbyrun.jar server shutdown 2009-05-08 17:07:25.887 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) shutdown
25
The server shutdown confirmation appears in both command windows. Activity notes The client connection URL contains network information (hostname and portnumber) not found in the URL for an embedded connection. This information tells the client driver the location of the Network Server. The client driver sends requests to and receives responses from the Network Server. In this activity the Derby database engine is embedded in the Network Server and returns data to the ij client (a client/server configuration). In contrast, establishing a connection using an embedded URL (one without //localhost:1527/) would have caused the Derby engine to be embedded in the ij application (an embedded configuration). In this configuration, multiple client programs can connect to the Network Server and access the database simultaneously. (This activity does not demonstrate this capability.)
> Important: Include the dot (.) at the end of each command so that your current working directory is included in the classpath and the files are copied to the correct location. 2. Compile the WwdEmbedded.java program.
javac WwdEmbedded.java
> Important: A command prompt appears if the compilation is successful. The binary file WwdEmbedded.class is created. If an error message appears, verify that the JDK is properly installed. 3. Run the program.
26
The WwdEmbedded.java program populates a table with wish-list items. The program prompts you for text input (up to 32 characters), stores the text input in a database table, and then lists the items stored in the table. The program continues to ask for wish-list items until the you type the command exit or a problem is encountered. Some basic information on program progress is displayed at the beginning and the end of the program.
java WwdEmbedded org.apache.derby.jdbc.EmbeddedDriver loaded. Connected to database jdbcDemoDB . . . . creating table WISH_LIST Enter wish-list item (enter exit to end): a peppermint stick __________________________________________________________ On 2009-05-08 13:12:09.058 I wished for a peppermint stick __________________________________________________________ Enter wish-list item (enter exit to end): a long vacation __________________________________________________________ On 2009-05-08 13:12:09.058 I wished for a peppermint stick On 2009-05-08 13:12:21.28 I wished for a long vacation __________________________________________________________ Enter wish-list item (enter exit to end): exit Closed connection Database shut down normally Getting Started With Derby JDBC program ending.
Define key variables and objects DEFINE VARIABLES SECTION: The initial lines of the main method define the variables and objects used in the program. This example uses variables to store the information needed to connect to the Derby database. The use of variables for this information makes it easy to adapt the program to other configurations and other databases. driver Stores the name of the Derby embedded driver. dbName Stores the name of the database. 27
connectionURL Stores the Derby connection URL that is used to access the database. createString Stores the SQL CREATE statement for the WISH_LIST table.
String driver = "org.apache.derby.jdbc.EmbeddedDriver"; String dbName="jdbcDemoDB"; String connectionURL = "jdbc:derby:" + dbName + ";create=true"; ... String createString = "CREATE TABLE WISH_LIST " + "(WISH_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY " ... + " WISH_ITEM VARCHAR(32) NOT NULL) " ;
Start the Derby engine LOAD DRIVER SECTION: Loading the Derby embedded JDBC driver starts the Derby database engine. The try and catch block (the Java error-handling construct) catches the exceptions that may occur. A problem here is usually due to an incorrect classpath setting.
String driver = "org.apache.derby.jdbc.EmbeddedDriver"; ... try { Class.forName(driver); } catch(java.lang.ClassNotFoundException e) { ... }
If you are using JDK 6 or higher, this code fragment is not needed, because you do not need to load the driver explicitly. In a JDK 6 environment, the driver loads automatically when you obtain a connection to the database. Boot the database BOOT DATABASE SECTION: The DriverManager class loads the database using the Derby connection URL stored in the variable connectionURL. This URL includes the parameter ;create=true so that the database will be created if it does not already exist. The primary try and catch block begins here. This construct handles errors for the database access code.
String connectionURL = "jdbc:derby:" + dbName + ";create=true"; ... try { conn = DriverManager.getConnection(connectionURL); ... <most of the program code is contained here> } catch (Throwable e) { ... }
Set up program to execute SQL INITIAL SQL SECTION: The program initializes the objects needed to perform subsequent SQL operations and checks to see if the required data table exists. The statement object s is initialized. If the utility method WwdUtils.wwdChk4Table does not find the WISH_LIST table, the statement object's execute method creates the table by executing the SQL stored in the variable createString.
s = conn.createStatement(); if (! WwdUtils.wwdChk4Table(conn)) { System.out.println (" . . . . creating table WISH_LIST"); s.execute(createString); }
28
The INSERT statement used to add data to the table is bound to the prepared statement object psInsert. The prepared statement uses the question mark parameter ? to represent the data that will be inserted by the user. The program sets the actual value to be inserted later on, before executing the SQL. This is the most efficient way to execute SQL statements that will be used multiple times.
psInsert = conn.prepareStatement ("insert into WISH_LIST(WISH_ITEM) values (?)");
Interact with the database ADD / DISPLAY RECORD SECTION: This section uses the utility method WwdUtils.getWishItem to gather information from the user. It then uses the objects set up previously to insert the data into the WISH_LIST table and then display all records. A standard do loop causes the program to repeat this series of steps until the user types exit. The data-related activities performed in this section are as follows: The setString method sets the substitution parameter of the psInsert object to the value typed by the user. Then the executeUpdate method performs the database insert.
psInsert.setString(1,answer); psInsert.executeUpdate();
The statement object s is used to select all the records in the WISH_LIST table and store them in the ResultSet named myWishes.
myWishes = s.executeQuery("select ENTRY_DATE, WISH_ITEM from WISH_LIST order by ENTRY_DATE");
The while loop reads each record in turn by calling the next method. The getTimestamp and getString methods return specific fields in the record in the proper format. The fields are displayed using rudimentary formatting.
while (myWishes.next()) { System.out.println("On " + myWishes.getTimestamp(1) + " I wished for " + myWishes.getString(2)); }
Shut down the database DATABASE SHUTDOWN SECTION: If an application starts the Derby engine, the application should shut down all databases before exiting. The attribute ;shutdown=true in the Derby connection URL performs the shutdown. When the Derby engine is shutdown, all booted databases will automatically shut down. The shutdown process cleans up records in the transaction log to ensure a faster startup the next time the database is booted. Tip: You can shut down individual databases without shutting down the engine by including the database name in the connection URL. "This section verifies that the embedded driver is being used, then issues the shutdown command and catches the shutdown exception to confirm that the Derby engine shut down cleanly. The shutdown status is displayed before the program exits.
if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) { boolean gotSQLExc = false; try { DriverManager.getConnection("jdbc:derby:;shutdown=true"); } catch (SQLException se) {
29
if ( se.getSQLState().equals("XJ015") ) { gotSQLExc = true; } } if (!gotSQLExc) { System.out.println("Database did not shut down normally"); } else { System.out.println("Database shut down normally"); } }
> Important: The XJ015 error (successful shutdown of the Derby engine) and the 08006 error (successful shutdown of a single database) are among the few exceptions thrown by Derby that indicate that an operation succeeded. Most other exceptions indicate that an operation failed. You should check the log file to be certain. The errorPrint and SQLExceptionPrint methods DERBY EXCEPTION REPORTING CLASSES: The two methods at the end of the file, errorPrint and SQLExceptionPrint, are generic exception-reporting methods that can be used with any JDBC program. This type of exception handling is required because often multiple exceptions (SQLException) are chained together and then thrown. A while loop is used to report on each error in the chain. The program starts this process by calling the errorPrint method from the catch block of the code that accesses the database.
// Beginning of the primary catch block: uses errorPrint method } catch (Throwable e) { /* Catch all exceptions and pass them to ** the exception reporting method */ System.out.println(" . . . exception thrown:"); errorPrint(e); }
The errorPrint method prints a stack trace for all exceptions except a SQLException. Each SQLException is passed to the SQLExceptionPrint method.
static void errorPrint(Throwable e) { if (e instanceof SQLException) SQLExceptionPrint((SQLException)e); else { System.out.println("A non SQL error occured."); e.printStackTrace(); } } // END errorPrint
The SQLExceptionPrint method iterates through each of the exceptions on the stack. For each error, the method displays the codes, message, and stacktrace.
// Iterates through a stack of SQLExceptions static void SQLExceptionPrint(SQLException sqle) { while (sqle != null) { System.out.println("\n---SQLException Caught---\n"); System.out.println("SQLState: " + (sqle).getSQLState()); System.out.println("Severity: " + (sqle).getErrorCode()); System.out.println("Message: " + (sqle).getMessage()); sqle.printStackTrace(); sqle = sqle.getNextException(); } } // END SQLExceptionPrint
To see the output produced by this method, type a wish-list item with more than 32 characters, such as I wish to see a Java program fail.
30
Activity 4: Create and run a JDBC program using the client driver and Network Server
This activity demonstrates the ease with which a program that embeds Derby can be modified for a client/server implementation that uses the Derby Network Server. This activity assumes you have performed the preceding activities and have a working directory called DERBYTUTOR, and have copies of the program files from the $DERBY_HOME/demo/programs/workingwithderby/ directory. A basic knowledge of the WwdEmbedded.java program and experience starting and connecting to the Network Server are helpful. You will need to use a text editor to create the WwdClient.java program. You will create a Derby client program, WwdClient.java, by changing a few lines of the WwdEmbedded.java program. You can run the client program in multiple command shells, allowing simultaneous update from two or more sources. You use two command windows (Server-Shell and Client-Shell) in this activity. You use the Server-Shell to start the Derby Network Server and display Network Server messages. You use the Client-Shell to edit, compile and run the newly created WwdClient.java program. You set the CLASSPATH environment variable in the Client-Shell to support the client JDBC program. 1. Create the WwdClient program using the following steps: a. Open a command window (Client-Shell). b. Change to the DERBYTUTOR directory. c. Make a copy of the WwdEmbedded.java program called WwdClient.java. Operating System UNIX (Korn Shell) Windows Command
cp WwdEmbedded.java WwdClient.java
d. Open the WwdClient.java file in a text editor and update the class name to reflect the new file name:
Original declaration public class WwdEmbedded New declaration public class WwdClient
e. Edit the DEFINE VARIABLES SECTION of the program so that the driver variable contains the name of the Derby client driver class and the connectionURL variable contains the hostname and port number of the Network Server.
Original definitions String driver = "org.apache.derby.jdbc.EmbeddedDriver"; String dbName="jdbcDemoDB"; String connectionURL = "jdbc:derby:" + dbName + ";create=true"; New definitions String driver = "org.apache.derby.jdbc.ClientDriver"; ... String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
31
javac WwdClient.java
A command prompt appears if the compilation is successful. The binary file WwdClient.class is created. If an error message appears, modify the line indicated so that it is identical to the example. 2. Set up the client/server environment using the following steps: a. Open a command window (Server-Shell). b. Change to the DERBYTUTOR directory. c. Start the Network Server: Operating System UNIX (Korn Shell) Command
java -jar $DERBY_HOME/lib/derbyrun.jar server start 2009-05-08 17:24:16.031 GMT : Security manager installed using the Basic server security policy. 2009-05-08 17:24:16.665 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) started and ready to accept connections on port 1527 java -jar %DERBY_HOME%\lib\derbyrun.jar server start 2009-05-08 17:24:16.031 GMT : Security manager installed using the Basic server security policy. 2009-05-08 17:24:16.665 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) started and ready to accept connections on port 1527
Windows
3. Run the client program using the following steps: a. Return to the Client-Shell window. b. If not already set, set the CLASSPATH environment variable to include the location of the file derbyclient.jar: Operating System UNIX (Korn Shell) Windows Command
export CLASSPATH=$DERBY_HOME/lib/derbyclient.jar:.
set CLASSPATH=%DERBY_HOME%\lib\derbyclient.jar;.
> Important: Include the dot (.) at the end of the command so that your current working directory is included in the classpath. c. Run the program:
java WwdClient org.apache.derby.jdbc.ClientDriver loaded. Connected to database jdbcDemoDB Enter wish-list item (enter exit to end): a sunny day __________________________________________________________ On 2009-05-08 13:12:09.058 I wished for a peppermint stick On 2009-05-08 13:12:21.28 I wished for a long vacation On 2009-05-08 13:27:22.581 I wished for a sunny day __________________________________________________________ Enter wish-list item (enter exit to end): a new car __________________________________________________________ On 2009-05-08 13:12:09.058 I wished for a peppermint stick On 2009-05-08 13:12:21.28 I wished for a long vacation On 2009-05-08 13:27:22.581 I wished for a sunny day On 2009-05-08 13:27:42.105 I wished for a new car __________________________________________________________
32
Enter wish-list item (enter exit to end): exit Closed connection Getting Started With Derby JDBC program ending.
4. Shut down the Network Server: Operating System UNIX (Korn Shell) Windows Command
java -jar $DERBY_HOME/lib/derbyrun.jar server shutdown 2009-05-08 17:28:47.171 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) shutdown java -jar %DERBY_HOME%\lib\derbyrun.jar server shutdown 2009-05-08 17:28:47.171 GMT : Apache Derby Network Server - 10.5.1.1 - (764942) shutdown
The server shutdown confirmation appears in both command windows. Activity notes In a client/server environment, the client program is often used from other computers on the network. Whenever a system accepts connections from other computers, there is a chance of abuse. To maintain security, the Derby Network Server defaults to accepting connections only from clients running on the local machine (localhost). Before this or any other Derby client program can access the Network Server from another machine, additional steps should be taken to secure the Network Server environment. Once secured, the Network Server can be safely configured to accept connections from other machines. Refer to the "Network Server security" and "Running the Network Server under the security manager" sections of the Java DB Server and Administration Guide for important information on securing the Network Server and enabling network connections. With the Network Server started, you can run the client program simultaneously in multiple windows. To demonstrate this, open two command windows and perform the substeps of the "Run the client program" step in each window. Both clients will operate without a problem. In contrast, it would not be possible for a program that uses the embedded driver (for example, WwdEmbedded.java) to access the database until the database or the Network Server is shut down. You may have noticed that the client program does not shut down the database. This is because the database is a shared resource in a client/server environment and, in most cases, should be shut down only when the Network Server is shut down. If multiple clients are accessing the database and one client shuts down the database, the remaining clients will encounter a failure the next time they attempt an SQL command. Derby's two architectures have caused confusion for some new Derby users, who mistakenly think that embedded is a single-user configuration. This is not true. The embedded driver supports multiple simultaneous connections, performs locking, and provides performance, integrity, and recoverability. Any application that uses the embedded driver can open multiple Derby connections and then provide a means for multiple users to interact with the database on each connection. The Derby Network Server is an example of such an application.
33
With this basic knowledge, you are ready to begin using Derby to address your own specific needs. As your next step in learning about this lightweight and powerful tool, visit the Apache Derby Web site. Use this link: Browser URL: WorkingWithDerby Resources page http://wiki.apache.org/db-derby/WorkingWithDerby
Activities summary We hope these activities have helped you understand the steps needed to create and access Derby databases. Although Derby is easy to set up and use, you will find that it has the features and reliability of much larger database systems. The examples presented here do not begin to scratch the surface of what can be done. Please take a few moments to become familiar with the many online resources available to Derby users and developers by browsing the Derby Web site at Apache. Whether you are performing a general evaluation of Derby or have a specific need to address, the link to the WorkingWithDerby resources page is a good stepping stone to finding additional information of interest: The Derby Quick Start page is a good reference page organized by area of interest. You will find that many content-rich areas, such as the Derby Wiki and the Derby Users mailing list, are available to you. If you are interested in how others are using Derby, see the Uses of Derby page on the Wiki. This page contains informational links to development projects and products that use Derby. When you implement a system using Derby, please add it to this list.
34
Embedded environment
An embedded environment is an environment in which only a single application can access a database at one time, and no network access occurs. When an application starts an instance of Derby within its JVM, the application runs in an embedded environment. Loading the embedded driver starts Derby.
Client/server environment
A client/server environment is an environment in which multiple applications connect to Derby over the network. Derby runs embedded in a server framework that allows multiple network connections. (The framework itself starts an instance of Derby and runs in an embedded environment. However, the client applications do not run in the embedded environment.) You can also embed Derby in any Java server framework. See the Java DB Server and Administration Guide for more information on how to run Derby on a server.
Available drivers
Different JDBC drivers are available depending on the environment you choose for Derby. org.apache.derby.jdbc.EmbeddedDriver A driver for embedded environments, when Derby runs in the same JVM as the application. org.apache.derby.jdbc.ClientDriver A driver for the Network Server environment. The Network Server sets up a client/server environment.
35
The format for the database connection URL for connecting to a database is:
jdbc:derby:databaseName;URLAttributes
where: databaseName The name of the database that you want to connect to URLAttributes One or more of the supported attributes of the database connection URL, such as ;territory=ll_CC or ;create=true. For more information, see the Java DB Developer's Guide. For the network client driver that is provided by Derby, the format for the database connection URL for connecting to a database is this:
jdbc:derby://server[:port]/databaseName[;URLAttributes=value[;...]]
where the server and port specify the host name (or IP address) and port number where the server is listening for requests and databaseName is the name of the database you want to connect to. The URLAttributes can be either Derby embedded or network client attributes. See the Java DB Server and Administration Guide for more information on accessing the Network Server by using the network client.
36
Documentation conventions
This section describes the terminology, syntax, and typographical conventions of the Derby documentation.
Terminology
The Derby documentation uses the specialized term environment to describe the method your application uses to interact with Derby. An environment is sometimes referred to as a framework. The two types of environments are the embedded environment and the client/server environment.
SQL syntax
SQL syntax is presented in modified BNF notation. The meta-symbols of BNF are: Symbol | [ ] * { } ( ) . , Meaning or. Choose one of the items Enclose optional items. Flags items that you can repeat 0 or more times. Has a special meaning in some SQL statements. Groups items so that they can be marked with one of the other symbols, i.e. [ ], |, or *. Other punctuation that is part of the syntax.
Command-line syntax for running Java programs and utilities (as well as examples) always begins with the word java:
java org.apache.derby.tools.ij
This documentation attempts to be JVM neutral, but any command line examples or syntax using JVM specific references should be verified with your JVM documentation.
Typographical conventions
This documentation uses some typographical conventions to highlight elements of the SQL language, operating system commands, and the Java programming language. Table 1. Derby typographical conventions Usage New terms Typeface Italic Examples defined by keys
37
Examples
In syntax, items that you Italic do not type exactly as they appear, but replace with the appropriate name SQL examples Java application examples Bold and/or fixed-width Bold and/or fixed-width Bold and/or fixed-width Bold and/or fixed-width All caps
SELECT city_name FROM Cities Connection conn = DriverManager.getConnection ("jdbc:derby:Sample") java org.apache.derby.tools.ij --This line ignored You can use a CREATE TABLE statement
Things you type in a command prompt Comments within examples SQL keywords (commands)
38
Use
You always need this library for embedded environments. For client/server environments, you only need this library on the server. Tools libraries For embedded environments, you need a library in the classpath to use a tool. For a client/server environment, you need a library on the client only. Library Names
derbytools.jar derbyrun.jar
Use
Required for running all the Derby tools (such as ij, dblook, and import/export). Executable jar file that can be used to start the Derby tools.
Use
Required to start the Derby Network Server.
Use
Required to use the Derby network client driver.
Use
derbyLocale_cs.jar Required to provide translated messages for the indicated locales. derbyLocale_de_DE.jar derbyLocale_es.jar derbyLocale_fr.jar derbyLocale_it.jar derbyLocale_hu.jar derbyLocale_ja_JP.jar derbyLocale_ko_KR.jar derbyLocale_pl.jar
39
40
Trademarks
The following terms are trademarks or registered trademarks of other companies and have been used in at least one of the documents in the Apache Derby documentation library: Cloudscape, DB2, DB2 Universal Database, DRDA, and IBM are trademarks of International Business Machines Corporation in the United States, other countries, or both. Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. UNIX is a registered trademark of The Open Group in the United States and other countries. Other company, product, or service names may be trademarks or service marks of others.
41