Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Sample Java Program Accessing a Database

In this lesson, we’ll illustrate how to create Java applications that can access a database. For this
lesson, we’ll use our existing friends database. We will create 2 Java programs: 

1. The first program (Display.java) will illustrate how  to retrieve information from the profile
table, a table in our friends’ database. In particular, the first program will retrieve the ID,
Firstname, M.I., Lastname, Cellphone, and Birthday fields from the profile table. 
2. The second program (Insert.java) will illustrate how to add a new friend to the database. 

To keep things organized, let’s put our new set of Java applications in a new project called FriendsDB.
Within the FriendsDB project, let’s create a new Java class named Display. Follow the screenshots
below in case you forgot how to create a class in a new project:

In the code window, remove all lines created by IntelliJ. Replace those lines with the following: 
You can run the Display class by right-clicking it the code window then choosing Run
‘Display.main()’
 

Displaying Friend Information (Display.java)


If you compare the sample Java application in Lesson 14 (App.java) with this
one (Display.java), you’ll notice that we borrowed some lines from App.java. 

The highlighted lines are the lines that establish connection to the MariaDB database named friends
using peter’s account. Just like what we did in Lesson 6, we must first open a connection to our
MariaDB database by passing the account name and password of the user who has a privilege to
access MariaDB database as well as the name of the database (In this example, we used the account
of peter, a MariaDB user we created in Lesson 5, who has a privilege over the database named
friends). Note that if we entered an invalid account then our Java program would not be able to
access MariaDB. The try-catch block is also present in both programs in order to handle exceptions.

The next lines are completely new and we give an overview of each statement group. The lines
are necessary to enable us to create and execute SQL queries. Statement objects allow us to
execute basic SQL queries and retrieve the results through the ResultSet class. 

To create a Statement instance, you call


the createStatement()method. The Statement methods executeQuery and getResultSe
t both return a ResultSet object. When we execute a query, we get back a ResultSet which
initially sets a cursor to point before the first row of data. In the given Java application,
the resultSet, which is an instance of ResultSet, contains the rows of friends retrieved from the
profile table.

We can then use the next()method of the ResultSet (i.e. resultSet.next() for this example) to


point to the next row. Since the cursor is initially positioned just above the first row of a object, the
first call to the method next()moves the cursor to the first row and makes it the current row.
Successive invocations of the method next()move the cursor down one row at a time from top to
bottom. To make sure that we navigate all records, we put the line resultSet.next()inside a
while loop as shown in this line:

The lines

retrieve column values from the current row. The ResultSet interface has a number of get methods
(ex. getBoolean, getLong, getInt, getString, getDate, and so on) for retrieving column
values from the current row. We should always use the get method corresponding to the appropriate
datatype. For example, the method for retrieving a value of SQL type VARCHAR is getString while for
a  FLOAT data type, there is a corresponding getFloat.

The while loops you see below

are used to pad spaces so that the results will be more organized when presented onscreen. Here, if
the length of the firstname, lastname or cellphone is less than 16 characters, then the
firstname, lastname, and cellphone are padded with spaces. For the middle initial (i.e., the mi field),
we also pad it with spaces so that the resulting length of the mi field is 10 characters.
 

The lines

print the ID, first name, middle initial, last name, cellphone, and birthday fields. If the ID is less than 10
(i.e the ID field is a 1-digit number), then after the ID field, it pads 4 spaces before displaying the first
name field. However, if the ID field is > 10 (i.e., the ID field is a 2-digit number), then after the ID field, it
pads only 3 spaces.

Finally, the line

closes our MariaDB connection. This is equivalent to logging out of MariaDB.

The import statements

have to be declared because we made a reference to the following SQL classes: Connection,


Statement, ResultSet, SQLException, Date which are all included in java.sql.*;.
We added the parameter zeroDateTimeBehavior=convertToNull in the URL to our database
since we have a date field (the birthday field is our date field) and this date field type cannot be
mapped to a Date java Object when it is null. If we did not include this parameter in our URL to
the database, then if we have a record with no birthday field, we would encounter this error:

This is because in MariaDB, if we have a field with a date data type and we did not assign a value for
that date data type, then MariaDB automatically assigns it a value of 0000-00-00. In MariaDB, a
null value for date is 0000-00-00 which is not compatible to Java’s representation of a date with
null value. So the easy way to get out of this and not get an error is by passing
"zeroDateTimeBehavior=convertToNull" as a parameter to the JDBC url. Without this
parameter, we would encounter an error since we have one record with no birthday (that’s Harry’s
record!).

Let’s try removing this parameter in the JDBC url. Did you get an error message similar to the one
below? Here, Java had no problem displaying the first 4 records. However, it had a problem with
Harry’s record since Harry has no birthday field.
So again, to solve this problem, always remember to include the parameter

in the JDBC url if you have a field with a date datatype.

Here’s the complete source code for Display.java including explanations for each group of
statements.
 

Adding a New Friend (Insert.java)


We have just described how to create a Java application that displays the contents of a table. Now
let’s discuss how to add new records. Just like what we did before, we need to create a new class
under our FriendsDB package. So click the New Class button. In the class name type Insert,
double-click the Insert class so you can go to the code window to type in the source codes.

In the code window of the Insert class, remove all lines created by IntelliJ. Replace those lines with
the following:
To determine if Luchie’s record is really in the database, open phpMyAdmin and browse all records
from the profile table. Did you see this?
So it’s clear that we have successfully inserted Luchie’s record in the profile table.

initializes our String variables (lastname, fi rstname, middleinit, address,


landline, cellphone, email, bday, and comments.) as well as our Date variable
(birthday). Note that we have a bday variable which is a String and a birthday variable which
is a Date data type. We’ll explain later why we need both variables.
are used to capture keyboard input. We placed the lines in a try-catch block in order to trap I/O
errors. The readLine() method of BufferedReader in the try block is used to read characters
typed in the keyboard.

In the code block


we aim to check if the first name, middle initial, and last name we gave is in the database. So we must
pass the first name, middle initial, and last name we gave in the SELECT query in order to determine
if the record is already in the database. We do this in order to be sure that we’re not adding a record
that is already in the database

Did you notice the question marks in the SELECT query?

The question marks (?) are place holders to values corresponding to firstname, middle initial, and
lastname. We were able to use this technique because we used a PreparedStatement.

PreparedStatement is derived from the more general class, Statement, that we already know from
previous example (Display.java). The two main advantage of PreparedStatement are:

 it is compiled and hence more efficient


 it can take parameters

That means we can use the same precompiled SQL statement and then just supply it with different
values each time we execute it!

As with Statement objects, we create PreparedStatement objects with a Connection method.


Hence the line

We need to supply values to be used in place of the question mark placeholders (if there are any)
before we can execute a PreparedStatement object. We do this by calling one of
the setXXX methods defined in the PreparedStatement class. If the value we want to substitute for a
question mark is a Java int, we call the method setInt. If the value we want to substitute for a
question mark is a Java String, we call the method setString, and so on. In general, there is
a setXXX method for each primitive type declared in the Java programming language.

The line

sets the first question mark placeholder with the value of firstname (Note: firstname is
the String variable that captured our keyboard input for first name)

The line

sets the second question mark placeholder with the value of middleinit (Note: middleinit is
the String variable that captured our keyboard input for middle initial.)

 
The line

sets the third question mark placeholder with the value of lastname (Note: lastname is
the String variable that captured our keyboard input for last name)

The line

executes the PreparedStatement named ps. The executeQuery() method is used whenever we


need to execute an SQL command that retrieves information from the database.
The executeQuery() of the PreparedStatement we used here is similar to the executeQuery()
method of Statement which we used in Display.java

The line

assigns to a ResultSet variable named resset the results of the SELECT query executed by


the PreparedStatement ps.

checks if the name given is already in the database. If the name is already there, it prints out the error
message “Oops, that record is already in the database! Sorry, you can’t add
an existing record” and then exits the program. Otherwise it asks us to input the address,
landline, cell phone, email, birthday, and comments.

Notice also that we treated birthday as a String (since we read the keyboard input for birthday
using readLine()) even though it is a Date. So the variable we used to capture birthday is bday
which is a String type.
are responsible for inserting the record into the profile table. Do you still remember
the SQL command to add records to a table?

The line

is an example of an SQL command that inserts a record into the profile table. Did you notice
the (?,?,?,?,?,?,?,?,?,?) after the word VALUES? These are placeholders to the fields ID,
lastname, firstname, … comments. Again we were able to use this technique because we
used a PreparedStatement.

The line

sets the first question mark place holder with the value to be determined by MariaDB since this first
parameter corresponds to the ID field which we defined as type int and having
an Auto_increment property set to true.

The line

sets the second question mark placeholder with the value of lastname (Note: lastname is
the String variable that captured our keyboard input for last name)

The line
sets the third question mark placeholder with the value of firstname (Note: firstname is
the String variable that captured our keyboard input for first name)

The line

sets the 9th question mark placeholder with the value of birthday (Note: birthday is a Date data
type. The value of birthday is obtained by converting the value of bday which is a String, to
a Date data type using the method valueOf().

The line

executes the PreparedStatement named prepstmt. The executeUpdate() method is called


whenever the SQL command to be executed will cause changes (i.e. additions, modifications,
deletions) to the records in the table. The executeUpdate() returns the number of rows affected by the
update statement. In this example, notice that no argument is supplied to executeUpdate when used
to execute prepstmt. This is because prepstmt already contains the SQL statement to be executed.

The line

assigns to an integer variable named row the total number of rows that were updated.

Here’s the complete source code for Insert.java including explanations for each group of
statements.
In this lesson, we’ll illustrate how to create Java applications that can update as well as delete
records from a table. Again, for this lesson, we’ll use our existing friends database. We will create
two Java programs: 

1. Th e first program (Update.java) will illustrate how to modify an existing record from the
profile table, a table in our friends’ database.
2. The second program (Delete.java) will illustrate how to delete an existing record from
the profile table.

Updating a Friend’s Record (Update.java)


Let’s start with Update.java. Open your FriendsDB project in IntelliJ IDEA. Let’s create a new
class. Let’s name this new class Update. Don’t forget to click the Ok button. 

In the code window, write the following code:


-

Here is how the Update program will look like when executed from within IntelliJ:

1. It first asks you to provide the first name, middle initial, and last name fields which will be
used in the search criteria.
2. If the record is found, the current information will be displayed.
3. Then you’ll be asked to update the record by inputting new values for each field.
4. Finally it will display a confirmation message that the record has indeed been modified.

In the screenshot below, we wanted to update Lot’s record. Assuming that we were able to enter Lot’s
personal info in the past, then his record exists and can therefore be retrieved. So, shown next is his
current personal info. To modify his record, we must supply updated information. Finally, a
confirmation message is displayed to indicate a successful record update.
 

Note that the Update operation is valid only for existing records. If the record to be updated is not in
the table, then the SQL Update statement can’t be executed.

In the example below, we wanted to update the record of our friend Rodolfo C. Jensen. However, we
never entered his personal data before so there is really nothing to update after all. So you get to see
an error message.

Here’s the source code for Update.java with explanations.


 
 

Deleting a Friend’s Record (Delete.java) 


To delete a specific record, we must first supply search criteria in order to verify that the record we
want to remove really exists. (It is not possible to delete something that is not there, right?) If the
record is there, then we can issue an SQL DELETE command to delete that record. Otherwise, we
display an error message, something like “Sorry, it is not possible to delete a nonexistent record!” 

The screenshot below illustrates how to delete a record. First we must supply the full name (i.e., first
name, middle initial, and last name). Only those records whose full name matches the full name we
specified will be selected. If there is a match, then the record is deleted and a confirmation message
is displayed to indicate a successful delete operation. See the example below.

Now suppose the record we wish to delete is not in the profile table, then an error message is
displayed. Th e screenshot shown below illustrates what happens when we attempt to delete a non-
existent record.

 
Here’s the source code for Delete.java with explanations.
 

Conclusion
We have reached the end of the lesson. In the last two lessons, we were able to describe how to
create Java applications that accesses a MariaDB database. In particular, we were able to create four
applications (Display.java, Insert.java, Update.java, and Delete.java) that illustrate how to display the
records, add new records, modify existing records, and delete existing records. Always remember
that:

1.  We need to register the JDBC driver for MariaDB, define the URL of the database we wish to
access, then connect to the database using the account of the user with appropriate privileges to
MariaDB. If any of these requirements are not met, then we will encounter a connection error.

2.  We need to create Statement objects since this contains the actual SQL commands that
manipulate the contents of the database.
 

3.  We can also create PreparedStatement objects that are precompiled and are capable of accepting
parameters.

4.  The ResultSet object contains the records retrieved upon issuance of an SQL SELECT statement.

5. To add a record:

a.  The record should be a new record (i.e., the record is not yet in the table) since it is wrong to add a
record that is already in the table. b. We issue an SQL INSERT command in order to add a new record.

6. To update a record:

a.  The record should be an old record (i.e., the record is an existing record) since it is wrong to update
a record that is not in the table. b.  We issue an SQL UPDATE command in order to modify an existing
record.

7. To delete a record:

a.  The record should be an old record (i.e., the record is an existing record) since it is wrong to delete
a record that is not in the table. b.  We issue an SQL DELETE command in order to delete an existing
record.

8. To retrieve a record(s):

a.  Just supply the search parameters in the SQL SELECT command. b. We issue an SQL SELECT
command in order to retrieve a record(s).

9.  We need to have error-handling routines in order to control the way our program responds to
errors.

You might also like