SQL and Java Connection - Complete - Version
SQL and Java Connection - Complete - Version
http://www.homeandlearn.co.uk/java/connect_to_a_database_using_java_code.html
In this section, you'll learn about Java databases. You'll create a simple database with one table, and learn how to connect to it using Java code.
Java uses something called JDBC (Java Database Connectivity) to connect to databases. There's a JDBC API, which is the programming part, and a JDBC
Driver Manager, which your programs use to connect to the database.
JDBC allows you to connect to a wide-range of databases (Oracle, MySQL, etc), but we're going to use the in-built database you get with the Java/NetBeans
software. 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.
To check that have everything you need, have a look at the Services tab in NetBeans. If you can't see the Services tab, click Window from the NetBeans
menu. From the Window menu, select Services. You should see something like this:
Expand the Databases item to see a Java DB item, a Drivers section, and a sample jdbc:derby sample item:
The idea is that you start the Java DB virtual server, and then create and manipulate databases on the server.
For the project in this section, we're going to set up a new database. You'll then learn how to connect to this database using Java code. The database we'll
create will be a simple one-table affair, rather than multiple tables connected together. You can indeed create multiple tables with Java DB, but we don't want
to complicate things unnecessarily.
The first thing to do is to start the server. So right click on Java DB. You'll see a menu appear. Select Start Server:
Have a look at the Output window and you'll see a few messages appear: (If you have a firewall running, you'll need to let the Java DB server through.)
Once the server is up and running you can create databases. You'll see how to do that in the next lesson.
Now that your server has been started, you can go ahead and create a database.
To create a new database, right click on Java DB again. From the menu that appears, select Create Database:
When you click on Create Database, you'll see a dialogue box appear:
Type a name for your database in the first box. Call it Employees. Type any User Name and Password:
Now that the database has been created, you need to create a table in the database. To do so, right click on your database. From the menu that appears
select Connect:
When a connection is made, you'll see some default folders for Tables, Views, and Procedures (see further down if your screen is not like this):
To create a new table in your database, right click the Tables folder. From the menu that appears, select Create Table:
If you don't see just the three folders above, but have something like this instead:
In the Table Name at the top, delete the default name of Untitled. Type a new name for your table. Call it Workers. You'll then have a table called Workers,
which is in the Employees database.
But you can't click OK just yet as the table has no columns in it. We want to create columns with the following names:
ID
First_Name
Last_Name
Job_Title
The ID column will hold a unique identifying number. This will identify a row in the table. A column with unique data in it is known as a Primary Key. Because
it's the Primary Key, the column has to hold data: It can't hold a null value. (A null value just means there's no information there.)
Click the button on the right, Add column. A new dialogue box pops up:
Name: ID
Type: Integer
Constraints: Primary Key, Unique
Click OK and you should be returned to the Create Table dialogue box:
We now have enough for the ID column in the table. Click the Add Column button on the right to add a new column to the table. Enter the following values for
this column (VARCHAR means a variable number of characters):
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: First_Name
Data Type: VARCHAR
Size: 20
For the third column in your table, enter the following values:
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: Last_Name
Data Type: VARCHAR
Size: 20
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: Job_Title
Data Type: VARCHAR
Size: 40
When you're finished, your Create Table dialogue box should look like this:
Click OK when you've entered all the information. Your table and table columns will then be created:
The next thing to do is to add some records to the database table. We'll do that next.
A database table is like a spreadsheet, in that it has rows and columns. Each row in our table has cells (fields) for an ID value, a First Name, a Last Name,
and a Job Title. Shortly, you'll learn how to write code to add new rows of information to the table. But you can use the NetBeans IDE to add rows as well.
To add a new row to your table, right click on your table name. From the menu that appears, select View Data:
When you click on View Data, you'll see a new window appear in the main NetBeans window
You use the bottom half of window to enter new table rows. The top half is for SQL Commands. (You'll learn more about them soon, when we've finished
adding rows.)
To add a new row, click the icon with the green plus symbol, in the bottom half of the window:
When your click the new row icon, a dialogue box appears:
As you can see, there are text boxes for each column in our table. For the ID column, we'll use sequential numbering, starting with 1. The second row in the
table will then have an ID of 2, the third row 3, etc. The numbers are not the row numbers: they are just unique values for each ID field. We could have easily
started with a value of 100 as the first ID number. The second number would then be 101, the third 102, etc.
ID: 1
First Name: Helen
Last Name: James
Job Title: IT Manager
Your dialogue box will then look like this:
Click OK when you're done and you'll be returned to the NetBeans window. The first row should then be displayed:
Add three more rows with the following data:
ID: 2
First Name: Eric
Last Name: Khan
Job Title: Programmer
ID: 3
First Name: Tommy
Last Name: Lee
Job Title: Systems Analyst
ID: 4
First Name: Priyanka
Last Name: Collins
Job Title: Programmer
When you've finished adding the new rows, your NetBeans window should look like this one:
In the previous lesson, you created records in your Java DB database table. In this lesson, you'll learn a few SQL commands so that you can manipulate
records in a table.
SQL stands for Structured Query Language, and is a way to query databases. You can select records, insert, delete, and update records, create tables,
drop tables, and more besides. It's quite a powerful tool.
SQL uses simple keywords to do the work. If you want to select all the records from a table, the words SELECT and FROM are used, along with the "all
records" symbol, which is *:
If you look at the top half of the NetBeans window, you'll see that a SELECT statement has already been set up: (NOTE: SQL is not case sensitive)
This says "Select all the records from the table called Workers". (The USER1 part, before the dot of Workers, is something called a Schema. This describes
the structure of the database, but also identifies things like users and the privileges they have. Don't worry about schemas, as we won't be going into them.)
In NetBeans, you run a SQL statement by clicking the Run button on the toolbar:
The results from the SQL statements are then displayed in the bottom half of the window:
After the keyword WHERE you need the name of a column from your table. You then type an equals sign, followed by a value. As an example, here's a SQL
statement that returns all the programmers in our table:
To try this SQL Statement out, right-click your table name in the Services area. From the menu that appears, select Execute Command:
When you click on Execute Command, a new window appears. Type the above SQL Statement, and then click the Run icon again:
The results will be displayed in the bottom half of the window:
As you can see, two rows are returned from the query.
You can also use the keyword LIKE with the WHERE clause. This then replaces the equals sign. LIKE is usually used with a wildcard character. The wildcard
character % means "any characters", for example, while an underscore is used for just a single character.
Instead of the equals sign or the keyword LIKE, you can also use the conditional operators (Greater Than, Less Than, etc.). If we had a salary column, we
could search for all workers who are getting paid more than 1000 a week:
Exercise
Try running the following SQL Statement:
We'll leave SQL Statements there, as we now have enough to start programming. We'll connect to this database and table again, using Java code this time
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 project database_console, and
the Main class DBConnect:
When you click Finish, your code should look like this:
Connecting to the Database
To connect to a database you need a Connection object. The Connection object uses a DriverManager. The DriverManager passes in your database
username, your password, and the location of the database.
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:
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:
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 … catch statement:
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 program 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\Java\jdk1.7.0_45\db\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.
In the next lesson, we'll continue with this Java database tutorial.
Databases: 1 2 3 4 5 6
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:
ResultSet rs = stmt.executeQuery( SQL );
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.
Because we've left the round brackets empty, we'll get the default RecordSet, which is TYPE_FORWARD_ONLY. In the next section, we'll use one of the other types. But
you use them like this (you don't need to add this to your code)::
So you first type the word RecordSet. After a dot, you add the RecordSet type you want to use.
However, it doesn't end there. If you want to use TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE you also need to specify whether the ResultSet is Read
Only or whether it is Updatable. You do this with two built-in constants: CONCUR_READ_ONLY and CONCUR_UPDATABLE. Again, these come after the word
RecordSet:
ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
This leads to a rather long line of code:
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:
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 program using forms and buttons to scroll
through the records.
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 and click Next.
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 Navigator area to the left of NetBeans. (If you can't see it, click Window > Navigator 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.
Connection con;
Statement stmt;
ResultSet rs;
Just below the Workers Constructor, add the following method:
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 program now. First, though, make sure to start your Java DB server from the Services window.
When you run your program, 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:
Move to the Next Record
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:
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
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 program 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 program 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 program 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.
<-- Databases and Java Forms | Move Back through a Java Database -->
The code for the Previous button is similar to theNext 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 tors.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".
<-- Scrolling Buttons | Move to the First and Last Records -->
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 tors.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".
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.
Updating a Record
The ResultSet has Update methods that allow you to update records not only in the ResultSet itself, but in the underlying database. Let's see how it works.
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):
Double click your Update button to create a code stub.
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:
There are quite a few different update methods to choose from. The one above usesupdateString. 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.
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.
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 );
btnDeleteRecord.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 );
btnDeleteRecord.setEnabled( true );
btnNewRecord.setEnabled( true );
btnSaveRecord.setEnabled( false );
btnCancelNewRecord.setEnabled( false );
Now run your program 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("");
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:
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" )) );
Now that the New and Cancel buttons have been set up, we can go ahead and save any new data entered into the Text Fields.
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:
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.
(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.
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.
And that's it for databases, and for this introduction to Java. It is a huge language that takes years to master. But we hope that this course has given you a
desire to learn more. If you got this far then your programming skills should be at an intermediate level. As a next step on your journey try developing one or
two small applications of your own. And, of course, keep reading, and keep studying. Good luck!