You are on page 1of 6

ITK 178 Database instructions 

Doug Twitchell 
 
This work is licensed under a Creative Commons Attribution‐Share Alike 3.0 United States License 

 
 
1. The database we will be using is Apache Derby, an open source, java‐based relational database.  
You can download the latest as a zip file from here. 
2. Once downloaded unzip the file into any directory.  This file contains everything 
necessary to run the database as well as all of its documentation. 
3. There are two folders you’ll need to be aware of.  The bin folder contains all of the executables 
for running derby.  The lib folder contains the jar files that include the Derby API. 
4. Attempt to start derby by double clicking on startNetworkServer.bat.  You should see a screen 
like this: 

 
 
5. Derby’s database server is now running. 
6. To test things out, let’s use Derby’s interactive SQL editor. This allows us to issue any SQL 
command to the derby server.  Double click on ij.bat, which is in the bin folder. You should see 
something like this: 

 
 
7. To connect to the database server we need to issue a connect command with a URL to the 
server.  Type or copy this into the command line:  
CONNECT 'jdbc:derby://localhost:1527/seconddb;create=true';
 
8. Notice that it is connecting to your local host, or your computer, at the same port it the server 
says it is running on.  Also notice that we are attempting to connect to a database called 
“seconddb”.  Since that database doesn’t yet exist on the server, we add the “create=true” to 
the end to tell the server to create the database if it does not exist.  After connecting , it should 
not say anything, but should look like this: 
 
 
9. Now that we are connected to a server and connected to a specific database named seconddb, 
we can make changes and issue queries.  This database has no tables and nothing in it.  So we 
have to create one.  Here’s the command to create a table called SECONDTABLE that has two 
columns one, a primary key, named ID, and one that can hold up to 14 characters named NAME: 
(notice: just like java, all SQL statements to Derby must end in a semicolon) 
CREATE TABLE SECONDTABLE
(ID INT PRIMARY KEY,
NAME VARCHAR(14));
 
10. After entering this command and pressing enter you should see the following: 

 
 
11. Now we have a table.  Now we should add data to that table.  Here’s the command  and the 
result: 
INSERT INTO SECONDTABLE VALUES
(100,'ONE HUNDRED'),(200,'TWO HUNDRED'),(300,'THREE HUNDRED');
 

 
 
12. That command added three rows to the table.  The first set of values entered 100 as the ID and 
“ONE HUNDRED” as the NAME.  Now we can query that same data.  Use the query below, and 
you should get the result below: 
 
SELECT * FROM SECONDTABLE;
 
 
13. I can also select a specific row using a WHERE clause: 
SELECT * FROM SECONDTABLE WHERE ID = 200;

 
 
14. To exit ij, type “exit;” and enter. Leave the server running. 
15. Now let’s get derby to work in Java.  Open eclipse and create a new Java project called 
“Database”.   
16. We need to add the Derby client jar files to the project so that it can find the Derby‐specific 
classes.  To do so, configure the build path of the project by right‐clicking on the project, 
choosing “Build Path”, and then “Configure Build Path…” as shown below: 
 
 
17. Go to the “Libraries” tab and choose “Add External JARs…”  Go to where you unzipped Derby 
and go to the “lib” directory and choose “derbyclient.jar” as shown below: 
 
 
18. Click Open to add the jar, and OK to close the build path configuration.   
19. Now you can write code that connects to your database.  Let’s do an example.   
20. Create a new class called TestDatabase and put in a main method. 
21. To make life easy put “import java.sql.*;” at the top.  java.sql.* is the package that holds all of 
the classes used to communicate with and handle data from databases.  Next, add the following 
code to the main method (you don’t have to add the comments.  They are part of the this 
tutorial): 
 
import java.sql.*;

/**
* Tutorial for using jdbc to connect to a derby database
* @author dtwitch
*/
public class TestDatabase {

public static void main(String[] args) {


//the name of the driver class
//this is only available if you include the derbyclient.jar as a library
String driver = "org.apache.derby.jdbc.ClientDriver";
//the name of the database we'll be connecting to
String dbName="seconddb";
//the url of the database. Looks just like what we used to connect using ij
String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
try {
Class.forName(driver); //this loads the driver class
//This statement actually connects to the database and
//gives us a Connection object which we'll use to create SQL statements
Connection conn = DriverManager.getConnection(connectionURL);

try {
//to execute a statement that changes the database, we'll create a Statement
//object and call "execute" on it.
Statement st1 = conn.createStatement();
//lets insert another row into our SECONDTABLE
st1.execute("INSERT INTO SECONDTABLE VALUES (400, 'FOUR HUNDRED')");

//now we can check to see if it worked by querying the database.


//when we query, we want the results so we use "executeQuery" and
//we are given a "ResultSet" object
String query = "SELECT * FROM SECONDTABLE WHERE ID = 400";
ResultSet rs = st1.executeQuery(query);
//Although we know there is only one result, there may not be, so we use a
//loop to get each row returned. The next() method moves us to the next row.
//the first time next() is called it moves to the first row, if there is one
System.out.println("Result of " + query + ": ");
while(rs.next()){
//we get the data using getXXX methods or ResultSet and we pass in
//either the colume name or the column index. We'll use the name this time
int x = rs.getInt("ID");
//we can get the row number using getRow().
//there are many methods on ResultSet that give you information about
//the results
System.out.println("Row " + rs.getRow() + ": " + x);
}
} finally{
//we always want our connection to the database to close when we
//are finished. Otherwise the database will hold that connection open
//until somekind of timeout occurs. If we leave too many open, the database
//may decide to refuse new connections
conn.close();
}

} catch (ClassNotFoundException e) {
// the Class.forname(driver) statement above tries to find the class
//located in the driver variable. If it doesn't exist this exception
//will be thrown. For now, we'll just print the stack
e.printStackTrace();
} catch (SQLException e) {
// Any other SQLExceptions are caught here. Any error returned by the
//database will be and SQLException. We'll just print them out.
e.printStackTrace();
}
}
}

22.  Use this as a template to create other programs that interact with your Derby database 
 
 
 

 
This work is licensed under the Creative Commons Attribution‐Share Alike 3.0 United States License. To 
view a copy of this license, visit http://creativecommons.org/licenses/by‐sa/3.0/us/ or send a letter to 
Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. 

You might also like