Building and Accessing a Relational DB using Netbeans

Relational / JDBC /SQL Notes
Building and Accessing a Relational DB using Netbeans
This note is to get you going on building a Relational database using Netbeans. The original intent
of this tutorial was to duplicate a ‘teaching’ database from the text by Elmarsi & Navathe database
text, 5th edition, figure 5.6 on page 159, the Company database. After doing that, I realized that
this tutorial is useful in building any relational database using the Netbeans IDE).[rob rucker 201308].
Using Netbeans (NB 6.9.1) allows me to partially automate the creation of a database, starting with
NB’s built in DBMS server (glassfish) and its’ included JavaDB database engine and templates.
Working through the tutorial below will let you create a database and then set up to create tables
and constraints within that DB using SQL scripts. This tutorial is in two major parts:
The first part shows how to create a database in NB, that is, by default, accessible over the internet.
Following this description I show Java code that would allow access to that DB, over the net using
a network driver.
The second part shows a NB project that embeds the above built DB. This works because when
you create a DB as described in the first part of this tutorial, the result is a ‘complete database in a
folder’. That folder can literally be copied to a new location, in this case, into a NB project. The
copied folder is a complete DB. The overall suggested approach is as below:
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 1 of 11
Creating a Network Database (
Relational / JDBC /SQL Notes
EER/UML Diagram/Plan out: DB context, name, tables, views,
constraints, row data
Create SQL scripts to create and populate tables,
views, constraints.
Start NB’s JavaDB engine and create a DB, say, Company
(NB will create a DB folder named Company that is self-contained
Execute SQL scripts to build your tables,
views, constraints, and indexes
**Test out your DB thoroughly within the NB environment by writing
SQL commands within this graphical Services context. Do this before
coding up your Java program!
Write Java Client code that accesses the DB using the same JDBC
code (network or embedded) but with the appropriate DB ‘driver’.
In our case this will require
creating a NB project and writing code within that project.
Write a Java Client using Network
access to Company.
Use the network driver:
org.apache.derby.jdbc.ClientDriver
Write a Java Client accessing the
Company DB folder copied to your project
Use the embedded driver:
org.apache.derby.jdbc.EmbeddedDriver
FIGURE 1. Overview of DB Creation and JDBC Access
As an illustration of how this can be done, I have created some SQL scripts with almost the same
data as shown in the text referenced above. (You are of course, free to create another named database and add tables to it as desired). There is a SQL script example showing table creation and data
loading below ( “SQL script example for the Employee table.” on page 4).
Note that this general approach will work for any DB creation using Netbeans. What will change
is the name of the database folder and the SQL scripts that will build the various tables within it.
The result in any case, is a Network DB, accessible over the net or embeddable within a project.
Creating a Network Database ( accessible over the net)
To create a DB within NB and create associated tables, do the following:
1. Fire up NB 6.9 + (I have 6.9.1 running glassfish 3.0.1) and, under the ‘Window’ menu, go to
Services
2. Under Databases, rt-clk on JavaDB and start server ( this will start the JavaDB server that
will listen for network requests on port 1527 ).
3. rt-clk on JavaDB again and select ‘properties’. The two properties of interest are the top line,
where the javadb distribution was installed, and the bottom line that can be edited by you to
place your databases wherever you like.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 2 of 11
Relational / JDBC /SQL Notes
Creating a Network Database (
4. In JavaDB, the ‘database’ consists of a named folder containing everything needed, placed in
the directory as specified by you). I put databases in a specific directory as shown. Note that
JavaDB databases will show up simply as a folder bearing the name you chose when you created the DB. You can see this folder in the Database Location target as shown in the properties dialog box as below.
5. Trouble and Hints: Note: If your options for starting the server are greyed out, then your JavaDB installation is probably wrong or non-existent. (Do a search for the folder ‘javadb’,
within your glassfish distribution (which has a bin and lib subdirectory), and then use that as
the JavaDB Installation target).
FIGURE 2. Select the JavaDB engine to use and where to place DBs
6. rt-clk on JavaDB and ‘create database’. Call it whatever: ‘Company’ is a convenient name
that I have used since my SQL scripts are targeted at creating a Company type database. For
user and password, use: APP and APP. Those will be used as the Schema name ‘APP’ and no
further configuration is then required since Derby uses these as defaults.
7. rt-clk on the newly created db icon and select ‘Connect’. The icon referred to here is the one in
the diagram that starts with ‘jdbc:derby . . . Company. . ‘ see screen shot below. When connected, the ‘broken arms’ will now be continuous.
8. rt-clk again on the newly created db icon and select ‘execute command’ - at this point the editor section will open awaiting a file input or direct typing input.
9. Navigate to your file of SQL script (or you could directly write SQL code here). You can navigate by simply doing an ‘Open file” and finding your SQL script. I have shown a script for
the company database EMPLOYEE table. Other scripts would build other tables.
10. Select the correct database to run the script against by going to a drop down menu above the
editor section labeled ‘connection’. Select your Company database icon.
11. rt-clk in the script editor area and select ‘Run File’ or use the icon that looks like a barrel with
a green arrow on it.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 3 of 11
Relational / JDBC /SQL Notes
Creating a Network Database (
FIGURE 3. SQL script example for the Employee table.
Note that lines 17,18,19 must be repeated when entering another set of data values.
12. The way I have the SQL script set up, I always do a complete drop of all the tables (in the
order that honors referential integrity constraints) and then rebuild them all. That means
before I build the tables the first time I will get an error since there is no table to drop. When
referential integrity constraints are required, you will have to build the tables without constraints and then go back and invoke Alter Table commands. That’s ok as long as the rest of
the build works.
NOTE: Once you have some tables with data, you can write SQL queries in the editor and run
them, which is a way to test out your queries.
Check out that the tables that have been built. I have built only the EMPLOYEE table for this little
tutorial.
Troubles: Sometimes, after multiple drops and builds, the Database manager becomes corupted
and even well formed code no longer runs. Unfortunately, the best I can come up with, is to shut
down NB and rebuild. This isn’t hard if you have written SQL scripts since they can simply be run
again against the new DB.
The next part of this tutorial will be some Java code that accesses this DB, and writes out data from
it. Note: In Java, you can do all the tasks such as create a DB and build, load, modify tables, but
usually this is done by another process, such as the NB helper programs and the SQL script I executed as above. In a production environment, the task of setting up and maintaining a DB is usually
done by a DBA (database administrator). which will be separate from the various personnel that
will want to access the DB.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 4 of 11
Relational / JDBC /SQL Notes
Creating a Network Database (
Java and other application programs are usually targeted to searching and retrieving and perhaps
some modification of data, from an already built DB.
Create a Project to Access the Network DB
In NB, create a Java project with the code below. (This tutorial assumes you can create a NB
project, set up a package directory, and then enter and test out code, such as that below). Note: the
proper derby jars must be in the project library ( derby.jar, derbyclient.jar) since those contain the
classes needed to run inside the JVM, to effect the DBMS. These jars are found in the javadb distribution folder. Look in Services > JavaDB >properties for their location sice they are part of the
javadb distribution and will be in that library.
JDBC Code to Access a Network JavaDB
/* JDBCNetworkAccess.java
* 2010-10-05 rob r.
*/
package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**JDBCNetworkAccess
* <h3> Design Intent </h3>
* <p> The intent of this class is to show how to access a network
accessible
* database from a Java client program. The database is of type JavaDB
and is assumed to be already built.
*An example DB has been built for this tutorial and is named
* (Company).
* This example also assumes that a table
* (EMPLOYEE) within that DB has been built with a few rows of data
* This program will then access that DB and print out rows of the
EMPLOYEE table.
* NOTE: In your own cases, You will need to modify the program below
* with the name of the your DB
* as well as the description
* of the table you are going to access. This can be done by looking at
the
* SQL build script.
* </p>
* @author rrucker
* @version 1.0
* @since jdk 1.6
* @see ""
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 5 of 11
Relational / JDBC /SQL Notes
Creating a Network Database (
*/
public class JDBCNetworkAccess
{
String networkDriver = "org.apache.derby.jdbc.ClientDriver";
String protocol = "jdbc:derby://localhost:1527/";
String database = "Company";//your named database
String user= "APP"; //user name used when creating database
String psw = "APP"; //password used when creating db
String schema = "APP."; // is the default schema (NOTE the “.” )
String tableName="EMPLOYEE";// replace with your table name
Connection connection;// make this an instance variable so it is
// visible throughout the file
/**accessDB () is a utility function simply used to connect
* to the db, then send a query that returns several rows of a table
* (see the main(method below for its use)
* @version 1.0
*/
public void accessDB() throws SQLException
{
try
{
Class.forName(networkDriver).newInstance();//load driver into memory
connection = DriverManager.getConnection(protocol+database,user,psw);
Statement stmt = connection.createStatement();//create a pipeline to
the db
String queryString = "SELECT * From " + schema + tableName;
ResultSet rs = stmt.executeQuery(queryString);//rs is a set of tuples
(rows)
System.out.println("****Printout of table: " + tableName + " rows
from DB: "+ database );
System.out.printf("%20s %7s %20s \n", "First Name","Initial", "Last
Name" );
while(rs.next()) // just get first few columns of the EMPLOYEE table
{
String firstName
= rs.getString("FName");// get first Name
String middleInitial
= rs.getString("MInit");//get middle
initial
String lastName
= rs.getString("LName");//get last name
System.out.printf("%20s %7s %20s \n", firstName, middleInitial,
lastName);
}//end while
}//end try
catch (Exception ex)
{
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 6 of 11
Relational / JDBC /SQL Notes
Setting up an Embedded DB
System.err.println("*** Error*** " + ex);
}//end catch
finally
{
if( connection !=null)
{
connection.close();
}
}//end finally
}//end accessDB()
/**main() causes the database to be connected and queried
* and then
* invokes the accessDB() method to do so
* @param args the command line arguments
*/
public static void main(String[] args)throws SQLException
{
new JDBCNetworkAccess().accessDB();
}//end main
}//end class JDBCNetworkAccess
Printout from the code above:
run:
****Printout of table: EMPLOYEE rows from DB: Company
First Name Initial
Last Name
James
E
Borg
Wong
T
Frank
John
B
Smith
Jennifer
S
Walllace
Ramesh
K
Narayan
Joyce
A
English
Alicia
J
Zelaya
Ahmad
V
Jabbar
Setting up an Embedded DB
Given you have created a DB, as in part one of this tutorial, such as Company. To access this DB
in embedded mode from inside a standalone project, you only need to copy its’ folder to the top
level of that project and invoke the ‘embedded’ version of the JavaDB(Derby) driver.
Note: JavaDB is a Sun/Oracle branded version of the Apache Foundataion’s
Derby relational database and most documentation uses the Derby name.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 7 of 11
Relational / JDBC /SQL Notes
Setting up an Embedded DB
Java Code to Access an Embedded DB
The code below shows how to access a stand-alone, embedded DB from inside a project. The context here is a NB project with the below code in its src directory. There are two Java programs here,
a controlling program Tester, and a data access program called AccessDB.
The Controlling Program, ‘Tester’
This program sets up a hard coded SQL query and sends it to a Data Access Program called AccessDB. AccessDB then invokes that query on the embedded DB and returns a set of rows of a table
or tables back to Tester, that are subsequently printed out. In this particular instance, I have set up
the code assuming the database is Company and the DB has a table named EMPLOYEE that I am
invoking the query upon.
/* Tester.java rrucker */
package demo;
import java.sql.ResultSet;
import java.sql.SQLException;
/**Tester
* <h3> Design Intent </h3>
* <p> The intent of this class is to access an embedded
* JavaDB using a supplied complete SQL query and return some
* rows. The DB was built using Netbeans tools and was
* literally copied to the project directory.
* The query string is hard coded here but could come from
* a GUI..<br> Tester then calls AccessDB which accepts the
* full SQL query, sends it to the embedded base and returns a result
set.
* </p>
* @author rrucker
* @version 1.0
* @since jdk 1.6
* @see AccessDB
*/
public class Tester
{
public static void main(String[] args)throws
SQLException
{
String query = "Select * from APP.EMPLOYEE ";
query += " where LName like '%' ";
AccessDB db = new AccessDB( query);
ResultSet rs = db.sendQuery();
while(rs.next())
{
System.out.println(rs.getString(1));
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 8 of 11
Relational / JDBC /SQL Notes
Setting up an Embedded DB
}//end while
}//end main
}//end class Tester
/* Output 2010-10-25
compile:
run:
Reading the Company Database (EMPLOYEE, DEPARTMENT. . .
Preparing to send query: Select * from APP.EMPLOYEE where LName like
'%'
James
Wong
John
Jennifer
Ramesh
Joyce
Alicia
Ahmad
BUILD SUCCESSFUL (total time: 1 second)
*/
The DB Access Program,
The program below, AccessDB, is called from a controller program Tester.java. Tester code is
shown after the code below. The role of Tester is to supply a complete SQL query that is to be invoked on the embedded DB, Company.
/* AccessDB.java rrucker */
package demo;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**AccessDB demonstrates. . . . . .
* <h3> Design Intent </h3>
* <p> The intent of this class is show how to read
tables
* <em>Company</em> DB
* This Company DB is accessed by the class AccessDB
* to read in the various tables.
* Tester.java is the controller program and has
* a hard coded SQL query string that is passed to the
* AccessDB program.
from
the
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r. page 9 of 11
Relational / JDBC /SQL Notes
Setting up an Embedded DB
* </p>
* @author rrucker
* @version 1.0 2010-10-25
* @since jdk 1.6
* @see Tester
*
*/
public class AccessDB
{ private Connection conn;
private Statement statement;
private ResultSet rs;
private String query; // complete SQL query captured in Tester
public AccessDB(String query)// query captured from Tester
{
this.query= query; // complete SQL query
}//end ctor
public ResultSet sendQuery() throws SQLException
{
setup();
System.out.println("Preparing to send query: " + query);
return rs = statement.executeQuery(query);
}//end getExecs
private void setup()
{
try{
/**loads driver*/
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
System.out.println("Reading the Company Database (EMPLOYEE, DEPARTMENT. . .");
String uid="APP";// uid and psw set for this db
// replace Company with your database name
String dbURL="jdbc:derby:Company; user=APP;password=APP";
conn=DriverManager.getConnection(dbURL);
statement = conn.createStatement();//prepare to send statements
}//end try
catch(Exception ex)
{
ex.printStackTrace();
}
}//end setup
}//end class AccessDB
Summary
Using an IDE such as Netbeans makes creation of databases and associated client code a productive process. This tutorial shows how to set up a NB database that is network accessible by default.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r.page 10 of 11
Relational / JDBC /SQL Notes
Setting up an Embedded DB
Due to the modular nature of JavaDB, the created DB is stored as a named folder, completely selfcontained. This folder may be literally copied to a project directory and then accessed as a standalone embedded database. Both modes are illustrated in this tutorial.
C:\acbooks\QPack2008\JDBCBuildRelationalDBandJDBCAccess.fm,9/3/13rob r.page 11 of 11