Java Database Handout
Java Database Handout
In a later section, you'll create a Java form that loads information from a database. The form will have Next and
Previous to scroll through the data. Individual records will then be displayed in text fields. We'll also add button
to Update a record, Delete a record, and create a new record in the database.
To get started, and for simplicity's sake, we'll use a terminal/console window to output the results from a
database.
So start a new project for this by clicking File > New Project from the NetBeans menu. Create a Java
Application. Call the package database_console, and the Main class DBConnect:
When you click Finish, your code should look like this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
So the DriverManager has a method called getConnection. This needs a host name (which is the location of
your database), a username, and a password. If a connection is successful, a Connection object is created, which
we've called con.
You can get the host address by looking at the Services tab on the left of NetBeans:
jdbc:derby://localhost:1527/Employees
The first part, jdbc:derby://localhost, is the database type and server that you're using. The 1527 is the port
number. The database is Employees. This can all go in a String variable:
Two more strings can be added for the username and password:
Add these three string before the connection object and your code would look like this:
As you can see in the image above, there is a wavy underline for the Connection code. The reason for this is
because we haven't trapped a specific error that will be thrown up when connecting to a database - the
SQLException error.
It's the DriverManager that attempts to connect to the database. If it fails (incorrect host address, for example)
then it will hand you back a SQLException error. You need to write code to deal with this potential error. In the
code below, we're trapping the error in catch part of the try catchstatement:
try {
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
In between the round brackets of catch, we've set up a SQLException object called err. We can then use
the getMessage method of this err object.
Add the above try catch block to your own code, and move your four connection lines of code to the try part.
Your code will then look like this:
If you do, it means you haven't connected to your database server. In which case, right click on Java DB in the
Services window. From the menu that appears, click Start Server:
You need to make sure that any firewall you may have is not blocking the connection to the server. A good
firewall will immediately display a message alerting you that something is trying to get through, and asking if
you want to allow or deny it. When you allow the connection, your NetBeans output window should print the
following message:
"Apache Derby Network Server - 10.4.1.3 - (648739) started and ready to accept connections on port
1527 at DATE_AND_TIME_HERE"
Once your server is started, run the programme again. There's a very good chance you'll get another error
message:
The reason for this error is that the DriverManager needs a Driver in order to connect to the database. Examples
of drivers are Client Drivers and Embedded Drivers. You can import one of these so that the DriverManager
can do its job.
Click on the Projects tab to the left of the Services window in NetBeans. (If you can't see a Projects tab,
click Window > Projects from the menu bar at the top of NetBeans.)
Locate your project and expand the entry. Right-click Libraries. From the menu that appears, select Add
Jar/Folder:
When you click on Add Jar/Folder a dialogue box appears. What you're doing here is adding a Java Archive file
to your project. But the JAR file you're adding is for the derby Client Drivers. So you need to locate this folder.
On a computer running Windows this will be in the following location:
C:\Program Files\Sun\JavaDB\lib
The file you're looking for is called derbyclient.jar. If you can't find it, or are using an operating system other
than Windows, then do a search for this file. Note the location of the file.
Click Open and the file will be added to your project library:
Now that you have a Client driver added to your project, run your programme again. You should now be error
free. (The Output window will just say Run, and Build Successful.)
In the next lesson, we'll continue with this Java database tutorial.
Connecting to a Database Table
Now that you have connected to the database, the next step is to access the table in your database. For this, you
need to execute a SQL Statement, and then manipulate all the rows and columns that were returned.
To execute a SQL statement on your table, you set up a Statement object. So add this import line to the top of
your code:
import java.sql.Statement;
In the try part of the try catch block add the following line (add it just below your Connection line):
Here, we're creating a Statement object called stmt. The Statement object needs a Connection object, with
the createStatment method.
We also need a SQL Statement for the Statement object to execute. So add this line to your code:
The above statement selects all the records from the database table called Workers.
We can pass this SQL query to a method of the Statement object called executeQuery. The Statement object
will then go to work gathering all the records that match our query.
However, the executeQuery method returns all the records in something called a ResultSet. Before we explain
what these are, add the following import line to the top of your code:
import java.sql.ResultSet;
Now add this line just below your SQL String line:
So our ResultSet object is called rs. This will hold all the records from the database table. Before we go any
further, though, here's an explanation of what ResultSets are.
ResultSets in Java
A ResultSet is a way to store and manipulate the records returned from a SQL query. ResultSets come in three
different types. The type you use depends on what you want to do with the data:
1. Do you just want to move forward through the records, from beginning to end?
2. Do you want to move forward AND backward through the records, as well as detecting any changes made to the
records?
3) Do you want to move forward AND backward through the records, but are not bothered about any changes
made to the records?
3. Do you want to move forward AND backward through the records, but are not bothered about any changes
made to the records?
Type number 1 on the list above is called a TYPE_FORWARD_ONLY ResultSet. Number 2 on the list is a
TYPE_SCROLL_SENSITIVE ResultSet. The third ResultSet option is called
TYPE_SCROLL_INSENSITIVE.
So you first type the word ResultSet. After a dot, you add the ResultSet type you want to use.
ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
One more thing to get used to with ResultSets is something called a Cursor. A Cursor is really just a pointer to
a table row. When you first load the records into a ResultSet, the Cursor is pointing to just before the first row
in the table. You then use methods to manipulate the Cursor. But the idea is to identify a particular row in your
table.
Using a ResultSet
Once you have all the records in a Results set, there are methods you can use to manipulate your records. Here
are the methods you'll use most often:
The ResultSet also has methods you can use to identify a particular column (field) in a row. You can do so
either by using the name of the column, or by using its index number. For our Workers table we set up four
columns. They had the following names: ID, First_Name, Last_Name, and Job_Title. The index numbers are
therefore 1, 2, 3, 4.
We set up the ID column to hold Integer values. The method you use to get at integer values in a column is
getInt:
Here, we've set up an integer variable called id_col. We then use the getInt method of our ResultSet object,
which is called rs. In between the round brackets, we have the name of the column. We could use the Index
number instead:
int id_col = rs.getInt(1);
Notice that the Index number doesn't have quote marks, but the name does.
For the other three columns in our database table, we set them up to hold Strings. We, therefore, need the
getString method:
Because the ResultSet Cursor is pointing to just before the first record when the data is loaded, we need to use
the next method to move to the first row. The following code will get the first record from the table:
rs.next( );
int id_col = rs.getInt("ID");
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
Notice that rs.next comes first in this code. This will move the Cursor to the first record in the table.
You can add a print line to your code to display the record in the Output window:
System.out.println( id_col + " " + first_name + " " + last_name + " " + job );
Here's what your code should look like now (we've adapted the print line because it's a bit too long):
If you want to go through all the records in the table, you can use a loop. Because the next method returns true
or false, you can use it as the condition for a while loop:
while ( rs.next( ) ) {
In between the round brackets of while we have rs.next. This will be true as long as the Cursor hasn't gone past
the last record in the table. If it has, rs.next will return a value of false, and the while loop will end. Using
rs.next like this will also move the Cursor along one record at a time. Here's the same code as above, but using a
while loop instead. Change your code to match:
When you run the above code, the Output window should display the following:
Now that you have an idea of how to connect to a database table and display records we'll move on and write a
more complex programme using forms and buttons to scroll through the records.
Databases and Java Forms
In this section, you'll create a form with buttons and text fields. The buttons will be used to scroll forwards and
backwards through the records in a database table. We'll also add buttons to perform other common database
tasks. The form you'll design will look something like this:
Start a new project for this by clicking File > New Project from the NetBeans menu. When the dialogue box
appears, select Java > Java Application. On step one of the dialogue box, type database_form as the Project
Name. Uncheck the box at the bottom for Create Main Class. Click the Finish button to create an empty
project.
In the Project area on the left locate your database_form project, and right click the entry. From the menu that
appears select New > JFrame Form:
When the dialogue box appears, type Workers for the Class name, and Employees as the package name. When
you click Finish, you should see a blank form appear in the main NetBeans window.
Add a Panel to your form. Then place four Text Fields on the panel. Delete the default text for the Text Fields,
leaving them all blank. Change the default variable names for the Text Fields to the following:
textID
textFirstName
textLastName
textJobTitle
Add a label to your panel. Position it just to the left of the job title Text Field. Enter "Job Title" as the text for
the label. Arrange the Text Fields and the Label so that your form looks something like this:
Now have a look at the Inspector area to the left of NetBeans. (If you can't see it, click Window >
Inspector from the NetBeans menu.) It should match ours:
What we want to do now is to have the first record from the database table appear in the text fields when the
form first loads. To do that, we can call a method from the form's Constructor.
First, though, we can add Client Driver JAR file to the project, just like last time. This will prevent any "Driver
Not Found" errors. So, in the Projects area, right click the Libraries entry for your project. From the menu that
appears, select Add JAR/Folder. When the dialogue box appears, locate the derbyclient.jar file. Then click Open
to add it to your project.
In the main NetBeans window, click the Source button at the top to get to your code. Now add the following
import statements near the top:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
You've met all these before, the first five from the previous section. The last one, JOptionPane, is so that we can
display error messages.
public Workers() {
initComponents();
DoConnect();
}
Your code window will then look like this: (Don't worry if you have underlines for the import statements.
Unless they're red underlines. In which case, you may have made a typing error.)
What we've done here is to set up a Connection object called con, a Statement object called stmt, and a
ResultSet object called rs. We've set them up at the top because our buttons will need access to these objects.
When the form loads, our DoConnect method will be called. We can add code here to connect to the database,
and display the first record in the text fields.
The code to add for the DoConnect method is almost identical to the code you wrote in the previous section. It's
this:
One line that you may not have met is this one:
Because the ID column is an Integer, we need to convert it to a String for the setText method of the Text Field.
We need to do this because Text Field's don't accept Integer values directly - you need to convert them to text.
All the other lines in the code should be familiar to you by now. Study the code to make sure you know what's
happening. Then add it your own DoConnect method.
You can run your programme now. First, though, make sure to start your Java DB server from the Services
window.
When you run your programme, you should see the first record displayed in the Text Fields:
Now that we have the first record displayed, we can add some buttons to scroll through the rest of the table data.
We'll do that in the next lesson.
Database Scrolling Buttons
What we'll do now is to add four buttons to the form. The buttons will enable us to move forward through the
records, move back, move to the last record, and move to the first record.
So add a new panel to your form. Enlarge it and then add for buttons to the panel. Change the variable names of
the buttons to the following:
btnNext
btnPrevious
btnLast
btnFirst
Change the text on each button the Next, Previous, Last, First. You form will then look something like this:
You need to do two things with the Next button: first, check if there is a next record to move to; and second, if
there is a next record, display it in the Text Fields. We can create an IF Statement for this. But it needs to be
wrapped up in a try catch block. So add the following to your Next button code stub:
try {
if ( rs.next( ) ) {
}
else {
rs.previous( );
JOptionPane.showMessageDialog(Workers.this, "End of File");
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(Workers.this, err.getMessage());
}
The IF Statement moves the ResultSet on one record at a time. If there isn't a next record then a value of false is
returned. The Else part moves the ResultSet back one record. That's because the Cursor will have moved past
the last record.
In the curly brackets for the IF Statement we can add the code to display the record in the Text Fields:
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first = rs.getString("First_Name");
String last = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
textID.setText(id);
textFirstName.setText(first);
textLastName.setText(last);
textJobTitle.setText(job);
This is the same code we have in our DoConnect method. (We could create a new method, so as not to duplicate
any code, but we'll keep it simple.)
The code for your Next button should now look like this:
When you've added your code, run your programme and test it out. Keep clicking your next button and you'll
scroll through all the records in the table. However, there is a problem.
When you get to the last record, you should see an error message appear:
The problem is that we've added an rs.previous line. However, we've used the default ResultSet type. As we
explained in the last section, this
gets you a ResultSet that can only move forward. We can use the type suggested in the error message.
Stop your programme and return to your coding window. In your DoConnect method, locate the following line:
stmt = con.createStatement( );
The ResultSet type will now allow us to scroll backwards as well as forwards.
Run your programme again. Click the Next button until you get to the last record. You should see the error
message from the try part of the try catch block appear:
In the next lesson, you'll learn how to backwards through your database records.
Move Back through a Java Database
The code for the Previous button is similar to the Next button. But instead of using rs.Next, you
use rs.Previous.
Return to the Design window and double click your Previous button to create a code stub.
Instead of typing out all that code again, simply copy and paste the code from your Next button. Then change
the rs.Next, in the IF statement to rs.Previous. Change the rs.Previous in the ELSE part to rs.Next. You can
also change your error message text from "End of File" to "Start of File".
Run your programme again. You should be able to move backward and forward through the database by
clicking your two buttons.
Move to the First and Last Records
Moving to the first and last records of your database is a lot easier.
Double click your First button to create the code stub. Now add the following code:
We have no need of an IF ... ELSE Statement, now. The only thing we need to do is move the Cursor to the first
record with rs.First, then display the first record in the Text Fields.
Similarly, add the following code for your Last button (you can copy and paste the code for the First button):
The only change to make is the use of rs.Last on the first line in place of rs.First.
When you've added the code, run your programme again. You should now be able to jump to the last record in
your database, and jump to the first record.
Make your form a bit longer. Now add a new panel to the form. Add a new button to the panel. Change the
default variable name to btnUpdateRecord. Change the text on the button to Update Record. We're also going
to have buttons to create a new record in the database, to save a record, cancel any updates, and to delete a
record. So add four more buttons to the panel. Make the following changes:
When you're done, your form should look something like this one (though feel free to rearrange the buttons):
The first thing to do is get the text from the Text Fields:
The Integer object has a method called parseInt. In between the round brackets of parseInt, you type the string
that you're trying to convert.
Now that we have all the data from the Text Fields, we can call the relevant update methods of the ResultSet
object:
rs.updateString( "First_Name", first );
There are quite a few different update methods to choose from. The one above uses updateString. But you
need the field type from your database table here. We have three strings (First_Name, Last_Name, Job_Title)
and one integer value (ID). So we need three updateStringmethods and one updateInt.
In between the round brackets of the update methods, you need the name of a column from your database
(though this can be its Index value instead). After a comma you type the replacement data. So, in the example
above, we want to update the First_Name column and replace it with the value held in the variable called first.
The update methods just update the ResultSet, however. To commit the changes to the database, you issue
an updateRow command:
rs.updateRow( );
Here are all the lines of code to update the ResultSet and the database table:
try {
rs.updateInt( "ID", newID );
rs.updateString( "First_Name", first );
rs.updateString( "last_Name", last );
rs.updateString( "Job_Title", job );
rs.updateRow( );
JOptionPane.showMessageDialog(Workers.this, "Updated");
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
Again, we need to wrap it all up in a try catch statement, just in case something goes wrong. Notice, too,
that we've added a message box for a successful update.
Run your programme and try it out. Change some data in a Text Field (Tommy to Timmy, for example). Then
click your Update button. Scroll past the record then go back. The change should still be there. Now close down
your programme and run it again. You should find that the changes are permanent.
If that's all a little confusing, try the following. Click on your Save New Record button to select it. In the
Properties area on the right, locate the Enabled property:
Uncheck the box to the right of enabled. The Save New Record will be disabled. Do the same for the Cancel
New Record button. The Cancel New Record will be disabled. When your form loads, it will look like this:
Even if you had code for these two buttons, nothing would happen if you clicked on either of them.
When the New Record button is clicked, we can disable the following buttons:
First
Previous
Next
Last
Update Record
Delete Record
New Record
The Save and Cancel buttons, however, can be enabled. If the user clicks Cancel, we can switch the buttons
back on again.
Double click your New Record button to create a code stub. Add the following lines of code:
btnFirst.setEnabled( false );
btnPrevious.setEnabled( false ) ;
btnNext.setEnabled( false );
btnLast.setEnabled( false );
btnUpdateRecord.setEnabled( false );
btnDelete.setEnabled( false );
btnNewRecord.setEnabled( false );
btnSaveRecord.setEnabled( true );
btnCancelNewRecord.setEnabled( true );
So seven of the buttons get turned off using the setEnabled property. Two of the buttons get turned on.
We can do the reverse for the Cancel button. Switch back to Design view. Double click your Cancel New
Record button to create a code stub. Add the following:
btnFirst.setEnabled( true );
btnPrevious.setEnabled( true ) ;
btnNext.setEnabled( true );
btnLast.setEnabled( true );
btnUpdateRecord.setEnabled( true );
btnDelete.setEnabled( true );
btnNewRecord.setEnabled( true );
btnSaveRecord.setEnabled( false );
btnCancelNewRecord.setEnabled( false );
Now run your programme and test it out. Click the New Record button and the form will look like this:
Click the Cancel New Record button and the form will look like this:
Another thing we need to do is to record which row is currently loaded. In other words, which row number is
currently loaded in the Text Fields. We need to do this because the Text Fields are going to be cleared. If the
Cancel button is clicked, then we can reload the data that was erased.
Add the following Integer variable to the top of your code, just below your Connection, Statement, and
ResultSet lines:
int curRow = 0;
To get which row the Cursor is currently pointing to there is a method called getRow. This allows you to store
the row number that the Cursor is currently on:
curRow = rs.getRow( );
We'll use this row number in the Cancel New Record code.
The only other thing we need to do for the New Record button is to clear the Text Fields. This is quite simple:
textFirstName.setText("");
textLastName.setText("");
textJobTitle.setText("");
textID.setText("");
For the Cancel button, we need to get the row that was previously loaded and put the data back in the Text
Fields.
To move the Cursor back to the row it was previously pointing to, we can use the absolute method:
rs.absolute( curRow );
The absolute method moves the Cursor to a fixed position in the ResultSet. We want to move it the value that
we stored in the variable curRow.
Now that Cursor is pointing at the correct row, we can load the data into the Text Fields:
textFirstName.setText( rs.getString("First_Name") );
textLastName.setText( rs.getString("Last_Name") );
textJobTitle.setText( rs.getString("Job_Title") );
textID.setText( Integer.toString( rs.getInt("ID" )) );
Click the New Record button to see the Text Fields cleared:
rs.moveToInsertRow( );
rs.updateInt("ID", newID);
rs.updateString("First_Name", first);
rs.updateString("Last_Name", last);
rs.updateString("Job_Title", job);
rs.insertRow( );
After adding the data to the ResultSet, the final line inserts a new row.
However, to commit any changes to the database what we'll do is to close our Statement object and our
ResultSet object. We can then reload everything. If we don't do this, there's a danger that the new record won't
get added, either to the ResultSet or the database. (This is due to the type of Driver we've used.)
stmt.close( );
rs.close( );
The code to reload everything is the same as the code you wrote when the form first loads:
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs.next( );
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first2 = rs.getString("First_Name");
String last2 = rs.getString("Last_Name");
String job2 = rs.getString("Job_Title");
textID.setText(id);
textFirstName.setText(first2);
textLastName.setText(last2);
textJobTitle.setText(job2);
You're not doing anything different, here: just selecting all the records again and putting the first one in the Text
Fields.
Here's all the code that saves a new record to the database (Obviously, a lot of this code could have went into a
method of its own):
The code is a bit long, but you can copy and paste a lot of it from your DoConnect method. (We've Photo-
shopped the stmt line because it's too big to fit on this page. Yours should go on one line).
(One other issue is that the ID column needs to be unique. Ideally, you'd write a routine to get the last ID
number, then add one to it. Other databases, like MySql, have an AutoIncrement value to take care of these
things. Just make sure that the ID value isn't one you have used before, otherwise you'll get an error message.
Or write a routine to get a unique ID!)
Run your programme and test it out. You now be able to save new records to your database.
rs.deleteRow( );
However, the Driver we are using, the ClientDriver, leaves a blank row in place of the data that was deleted. If
you try to move to that row using your Next or Previous buttons, the ID Text Field will have a 0 in it, and all the
others will be blank.
To solve this problem we'll first delete a row then, again, close the Statement object and the ResultSet objects.
We can then reload all the data in the Text Fields. That way, we won't have any blank rows.
Run your programme and test it out. You now be able to delete records from your database.
And that's it - you now have the basic knowledge to write a database programme in Java using a GUI.
Congratulations, if you got this far!