Define key variables and objects
Getting Started with Derby
29
within the program code and serve as cross-reference points between this section and
the Java program. The program uses methods from the
WwdUtils
class. The utility class
code is not described here but is available for review in the file
WwdUtils.java
.
Initialize the program
INITIALIZATION SECTION: The initial lines of code identify the Java packages used in
the program, then set up the Java class
WwdEmbedded
and the
main
method signature.
Refer to a Java programming guide for information on these program constructs.
import java.sql.*;
public class WwdEmbedded
{
public static void main(String[] args)
{
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.
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) {
...
}
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.