Java and Databases
Java and Databases
From:
https://play.google.com/store/apps/details
?id=com.java.offline
About Java and Databases
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• The database is called Java DB, a version of Apache
Derby.
• It runs on a virtual server, which you can stop and
start from within NetBeans
• Services tab in NetBeans
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Starting the Virtual Server
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Creating a Database with Java
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you click on Create Database, you'll
see a dialogue box appear:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Type a name for your database in the first
box. Call it Employees. Type any User
Name and Password
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Click OK to create your database. It should
then appear on the list:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Creating a Table in the Database
From:
https://play.google.com/store/apps/details
?id=com.java.offline
To create a new table in your database,
right click the Tables folder. From the menu
that appears, select Create Table:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Adding Records to a Java Database Table
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you click on View Data, you'll see a
new window appear in the main NetBeans
window
From:
https://play.google.com/store/apps/details
?id=com.java.offline
To add a new row, click the icon with the
green plus symbol, in the bottom half of
the window:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When your click the new row icon, a
dialogue box appears:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Click OK when you're done and you'll be
returned to the NetBeans window. The first
row should then be displayed:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you've finished adding the new
rows, your NetBeans window should look
like this one:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
SQL Commands
From:
https://play.google.com/store/apps/details
?id=com.java.offline
The results will be displayed in the bottom
half of the window:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Connect to a Database Using Java Code
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Connecting to the Database
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• the address of the highlighted database above is:
• 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:
• String host = "jdbc:derby://localhost:1527/Employees";
• Two more strings can be added for the username and
password:
• String uName = "Your_Username_Here";
String uPass= " Your_Password_Here ";
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Add these three string before the
connection object and your code would
look like this:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
In the code below, we're trapping the error in
catch part of the try … catch statement:
try {
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
From:
https://play.google.com/store/apps/details
?id=com.java.offline
You may get this error message in the
console window:
"java.net.ConnectException : Error connecting to
server localhost on port 1527 with message
Connection refused: connect."
From:
https://play.google.com/store/apps/details
?id=com.java.offline
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:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you allow the connection, your
NetBeans output window should print the
following message:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Once your server is started, run the
programme again. There's a very good
chance you'll get another error message:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Locate your project and expand the entry. Right-
click Libraries. From the menu that appears,
selectAdd Jar/Folder:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
On a computer running Windows this will
be in the following location:
C:\Program Files\Sun\JavaDB\lib
From:
https://play.google.com/store/apps/details
?id=com.java.offline
In the dialogue box, select
the derbyclient.jar file:
• Click Open and the file
will be added to your
project library:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Connecting to a Database Table
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Database Scrolling Buttons
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Change the text on each button the Next,
Previous, Last, First. You form will then look
something like this:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
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());
}
From:
https://play.google.com/store/apps/details
?id=com.java.offline
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);
From:
https://play.google.com/store/apps/details
?id=com.java.offline
The code for your Next button should now
look like this:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you get to the last record, you
should see an error message appear:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• In your DoConnect method, locate the following line:
stmt = con.createStatement( );
• Change it to this (yours need to go on one line):
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE );
• The ResultSet type will now allow us to scroll
backwards as well as forwards.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
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:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Move Back through a Java Database
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Move to the First and Last Records
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
The only change to make is the use of rs.Last on
the first line in place of rs.First.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Updating a Record
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• add four more buttons to the panel. Make the
following changes:
• Button Variable Name: btnNewRecord
Button Text: New Record
• Button Variable Name: btnDeleteRecord
Button Text: Delete Record
• Button Variable Name: btnSaveRecord
Button Text: Save New Record
• Button Variable Name: btnCancelNewRecord
Button Text: Cancel New Record
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Double click your Update button to create a code stub.
• The first thing to do is get the text from the Text Fields:
String first = textFirstName.getText( );
String last = textLastName.getText( );
String job = textJobTitle.getText( );
String ID = textID.getText( );
• If we want to update an ID field, however, we need to
convert the String to an Integer:
int newID = Integer.parseInt( ID );
• 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.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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 updateString methods and oneupdateInt.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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( );
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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() );
}
From:
https://play.google.com/store/apps/details
?id=com.java.offline
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Add a New Record
• We have three buttons that refer to new records: New
Record, Save New Record, and Cancel New Record.
• The New Record button will only clear the Text Fields,
and ready them for new data to be entered.
• We can also disable some other buttons, including the
New Record button.
• Another thing we can do is to make a note of which
record is currently loaded.
• If a user changes his or her mind, we can enable all the
buttons again by clicking the Cancel button.
• Clicking the Save New Record button will do the real
work of saving the data to the database.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Click on your Save New Record button to select it. In the
Properties area on the right, locate the Enabled
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
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 );
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Click the Cancel New Record button and
the form will look like this:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
The top of your code should
look like this:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Now go back to your New Record code
• 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("");
• Setting the Text property to a blank string.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Because we've used a
method of the ResultSet,
we need to wrap
everything up in a try …
catchblock. Here's what
the code should look like
for your New Record
button:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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" )) );
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Wrapping it all in a try …
catch block gives us the
following code:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
When you run the program…
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Clicking the Cancel
button will reload the
data:
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Save a New Record
• Before you can save a new record, you have to move the Cursor to
something called the Insert Row. This creates a blank record in the
ResultSet. You then add the data to the ResultSet:
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.)
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• To close a Statement or a ResultSet, you just issue the close command:
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);
String sql = "SELECT * FROM Workers";
rs = stmt.executeQuery(sql);
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);
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• 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):
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• (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 program and test it
out. You now be able to save
new records to your
database.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
Delete a Record
• Deleting a row can be straightforward: Just use
deleteRow method of the ResultSet:
• 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.
From:
https://play.google.com/store/apps/details
?id=com.java.offline
• Here's the code to
add for your
Delete Record
button:
• and…
• Run your program
and test it out.
You now be able
to delete records
from your
database.
From:
https://play.google.com/store/apps/details
?id=com.java.offline