You are on page 1of 52

1

AACS 3104
Chapter 4
Java Database Programming
2
Objectives
To become familiar with the JDBC API (1.0).
To learn how to load a driver, connect to a
database, execute statements, and process result
sets using JDBC (2.0).
To use the prepared statements to execute
precompiled SQL statements (3.0).
To process updateable and scrollable result sets.
(4.0)
3
1.0 The Design and use of JBDC
The Java API (Application Programming Interface) for
developing Java Database applications is called J DBC.

JDBC provides Java programmers with a uniform interface
for accessing and manipulating a wide range of relational
databases.

Using the JDBC API, applications written in Java
programming language can
execute SQL statements,
retrieve results,
present data in a user friendly interface, and
propagates changes back to the database.
4
1.0 The Design and use of JBDC (Contd)
The relationship between Java program, JDBC API, JDBC
drivers, and relational database are shown below.

Java Programs
JDBC API
MySQL JDBC
Driver
Microsoft
Access
Database
JDBC-ODBC
Bridge Driver
Oracle JDBC
Driver
MySQL
Database
Oracle
Database
Microsoft ODBC
Driver
This chapter
will cover how
to connect to
MS Access
Database Only
5
1.0 The Design and use of JBDC (Contd)
Java Programs
JDBC API
MySQL JDBC
Driver
Microsoft
Access
Database
JDBC-ODBC
Bridge Driver
Oracle JDBC
Driver
MySQL
Database
Oracle
Database
Microsoft ODBC
Driver
JDBC API is a set of interfaces
and classes used to write Java
programs for accessing and
manipulating relational databases.
JDBC drivers are database-
specific and are normally
provided by the database
vendors.
6
1.0 The Design and use of JBDC (Contd)
Table below shows the Database driver for different database
vendor.
Database Database Driver
MySQL MySQL JDBC driver (can be downloaded online)
Oracle Oracle JDBC drivers (can be downloaded online)
Ms Access JDBC-ODBC driver ( included in JDK )
ODBC is a technology developed by Microsoft for accessing
databases on the Windows platform
An ODBC driver is preinstalled on Windows.
The JDBC-ODBC bridge driver allows a Java program to access
any ODBC data source.
7
2.0 Connecting to and Querying a Database
2.1 J DBC Application Programming Interface (API)
Driver
Connection
Statements
ResultSet
2.2 Steps in connecting and querying a database
Step 1: Loading Driver
Step 2: Establishing Connection
Step 3: Creating and Executing Statements
Step 4: Processing ResultSet object
2.3 Example
8
2.1 J DBC Application Programming I nterface (API )

The JDBC API consists of classes and interfaces
for
Establishing connections with databases,
Sending SQL statements to databases,
Processing the results of the SQL statements
and etc.

Four (4) key interfaces are needed to develop any
database application using Java:
1. Driver
2. Connection
3. Statements
4. ResultSet
9
2.1 J DBC Application Programming I nterface (API )


Driver
Connection Connection
Statement Statement Statement Statement
ResultSet ResultSet ResultSet ResultSet
Creating and
executing
statements

Establishing
connections

Processing
ResultSet
Load Driver

The relationship of the 4 interfaces is shown in Figure 4.2.
Figure 4.2 Relationships between Driver, Connection, Statement
and ResultSet.
10
2.2 Steps in connecting and querying a database

The JDBC interfaces and classes are the building blocks in
the development of Java database programs
A typical Java program takes the following steps to access
the database:
Step 1:
Loading driver
Step 2:
Establish connection
Step 3:
Create and Execute statement
Step 4:
Process resultset
11
An appropriate driver must be loaded using the statement shown below
before connecting a database.
The Driver class for MS Access is sun.jdbc.odbc.JdbcOdbcDriver

Statement to load a driver:
Class.forName(<JDBCDriverClass>");

A driver is a class. For example:

Database Driver Class Source
Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK

NOTE: The JDBC-ODBC driver for Access is bundled in JDK.
Loading
drivers

Establishing
connections

Creating and
executing
Statements

Processing
ResultSet
put in here
2.2 Steps in connecting and querying a database (Contd)
12


A connection is like a cable that links your program to a
database.
To connect to a database, use the static method
getConnection(databaseURL) in the DriverManager class

Connection connection =
DriverManager.getConnection(databaseURL);

Database URL Pattern
Access jdbc:odbc:dataSource
See Appendix A in Lecture Note
for creating an ODBC data source
Loading
drivers

Establishing
connections

Creating and
executing
Statements

Processing
ResultSet
put in here
2.2 Steps in connecting and querying a database (Contd)
13
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Example:
Suppose a data source named CustomerDB has been
created for a MS Access database
we create the connection as follows:

Connection conCustomer =
DriverManager.getConnection("jdbc:odbc:CustomerDB");

2.2 Steps in connecting and querying a database (Contd)
14



An object of Statement can be viewed as a cart that
delivers SQL statements for execution by the database and
brings back the result back to the program.

Statement statement = connection.createStatement( );

Where
connection is Connection object created.
2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
15
Once a Statement object is created, we can use it to
execute executing SQL statements.












2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
SQL Types Statement method used
INSERT, UPDATE
and DELETE
executeUpdate( String sql)
SELECT query
NOTE:
query result is stored
in ResultSet object

executeQuery (String sql) : ResultSet
16
Lets assume that we have a table called Customers with
the following fields:
Customers (cust_ID, cust_Name, cust_Address)

To INSERT new customer:

Statement stmtInsert = conCustomer.createStatement();
stmtInsert.executeUpdate(INSERT INTO Customers
VALUES(C100, Adam, KL));

2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Use executeUpdate() method because we want to
INSERT record
17
2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Lets assume that we have a table called Customers with
the following fields:
Customers (cust_ID, cust_Name, cust_Address)

To query (SELECT)customer record

Statement stmtSelect = conCustomer.createStatement();
ResultSet rsCustomer; // declare ResultSet object to store query result

// select all customer record
rsCustomer = stmtSelect.executeQuery (SELECT * FROM
Customers);
//then we can process the result in rsCustomer later, see step 4

18
The ResultSet maintains a table whose current row
can be retrieved.
The initial row position is null.
A default ResultSet object is NOT updatable and has a
cursor that moves forward ONLY.


2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
19
Some useful methods in ResultSet:


2.2 Steps in connecting and querying a database (Contd)
Methods Description
next() Moves the cursor to the
next row.
Returns false if there are
no more rows in the
ResultSet object
getXxx( int ColumnIndex) : Xxx Retrieves the value at the
specified column index as
Xxx type value
getXxx ( String columnName) : Xxx Retrieves the value at the
specified column index as
Xxx type value
Column index in ResultSet starts from 1 (ONE)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
20
Example:
rsCustomer.next() // move cursor to next row

// get String value from 1
st
column in result set and store in a
// String variable
String customerID = rsCustomer.getString(1);

OR

// get String value from Column name Cust_Name in result set
// and store in a String variable
String customerName = rsCustomer.getString(Cust_Name);

2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
21
Lets assume that we have a table called Customers with the
following fields:
Customers(cust_ID, cust_Name, cust_Address)

To query (SELECT)customer record
Statement stmtSelect = conCustomer.createStatement();
ResultSet rsCustomer; // declare ResultSet object to store query result
// select all customer names
rsCustomer = stmtSelect.executeQuery(SELECT cust_Name FROM
Customers);
// loop through the resultset and display the customer names
while( rsCustomer.next() )
{ // display customer name on the console
System.out.println(name: + rsCustomer.getString(1) );
}
2.2 Steps in connecting and querying a database (Contd)
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
22
2.3 Example: connecting and querying MS Access Database

Example 1:
The program in Listing 4.1 connects to an ODBC
data source named CustomerDB and makes query
to all customers record.
(See Appendix A [ Page 22 in lecture note ] on how to
create ODBC data source)
It then displays all the customer names in the
console.
The Customers table in CustomerDB is as follows:
Customers( Cust_ID, Cust_Name, Cust_Address )
Run SimpleJDBC view SimpleJDBC code
HOW TO create
ODBC data source
23
2.3 Example: connecting and querying MS Access Database

Example 2:
The program in Listing 4.2 ( in lecture note)
demonstrates how to connect and make query to
database in GUI application
The program allows user to enter customer id to
look for customer details.
The sample output of program in Listing 4.2 is
shown below.
Run SearchCustomer
SearchCustomer code
24
2.3 Example: connecting and querying MS Access Database

Example 3:
Retrieve data from Database and bind them to a Combo Box
// in the constructor in GUI application
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection conCustomer =
DriverManager.getConnection(jdbc:odbc:CustomerDB);
Statement stmtCustomer= conStudent.createStatement();

ResultSet rsCustomer= stmtCustomer.executeQuery("SELECT Cust_ID FROM
Customers");
while( rsCustomer.next() )
{ String custID = rsCustomer.getString(1); // get Cust_ID value
// need to convert String value to Object ,
// this is because the addItem(Object o) method only accept Object type value
jcboCustomerID.addItem( (Object)custID);
}
25
3.0 PreparedStatement
The Statement interface is used to execute static
(fixed) SQL statements that contains NO parameters

In order words, you MUST already specified the values
in the condition in the WHERE clause.

However, Java also provides the PreparedStatement,
which extending Statement and can be used to
execute a precompiled SQL statement with or without
parameters.
26
3.0 PreparedStatement (Contd)
Since the SQL statements are precompiled,
they are efficient for repeated executions
27
3.0 PreparedStatement (Contd)
The PreparedStatement object is created using the
prepareStatement(String sql) method in the Connection
interface.
String sqlSelect = Insert Into Customer (Cust_ID, Cust_Name,
Cust_Address) Values(?, ?, ? );

PreparedStatement pstmt = connection.prepareStatement(sqlSelect);
The INSERT statement has 3 question marks (?) as
placeholders for parameters representing values for
Cust_ID, Cust_Name, Cust_Address in a record of the
Customer table.
28
3.0 PreparedStatement (Contd)
PreparedStatement interface provides methods to set the
values of the parameters in the object of PreparedStatement.
In general, the set methods have the following name and
signature:
setX( int parameterIndex, X value);
where
parameterIndex is the index of the parameter in the statement
X is the type of the parameter
For example:
setString(2 , adam );
// set the 2nd parameter value to a String value adam
29
3.0 PreparedStatement (Contd)
Lets see a more complete example:
The following codes pass the parameters C007, Jeverson ,
PJ to the placeholder for Cust_ID, Cust_Name and
Cust_Address in the PreparedStatement pstmt declared just now.
String sqlSelect = Insert Into Customer (Cust_ID, Cust_Name,
Cust_Address) Values(?, ?, ? );

PreparedStatement pstmt =
connection.prepareStatement(sqlSelect);

pstmt.setString(1 , C007 );
pstmt.setString(2 , Jeverson );
Pstmt.setString(3 , PJ );
30
3.0 PreparedStatement (Contd)
After setting the parameters, you can execute the
prepared statement by calling
executeQuery() [ for SELECT statement], OR
executeUpdate() [ for UPDATE, INSERT and DELETE
statement ].
31
3.0 PreparedStatement (Contd)
Example 4: Insert Customer record using
PreparedStatement object
Sample output

Run InsertCustomerPreparedStatement
InsertCustomerPreparedStatement Code
32
3.0 PreparedStatement (Contd)
HOW DOES IT WORK?
From line 8 12,
the necessary JTextFields and JButtons are declared.
In line 15,
a PreparedStatement object called pstmtCustomer is declared.
It is declared as data member so that its lifetime and scope
starts when the program starts and ends when the program
ends.
33
3.0 PreparedStatement (Contd)
Then in the constructor, it does the following:
1. call the initializedDB() method
From line 49 65, 1st load the driver, then establish the
connection.
Then create a String object to store the INSERT SQL statement.
Then create the PreparedStatement object pstmtCustomer
object by calling the prepareStatement() method from
Connection object and pass in the SQL string value.
34
3.0 PreparedStatement (Contd)
Then in the constructor, it does the following:
2. setup GUI components, add them to JFrame
3. addActionListener for the 2 buttons, namely jbtAdd and
jbtClear
in addCustomer method for jbtAdd
get textfield value accordingly
Call setString() method of PreparedStatement object to set
the parameter values.
Call executeUpdate() method to update the INSERT
statement to database.
35
4.0 Scrollable and Updateable ResultSet
The ResultSet used in the preceding examples are
sequentially forward reading.
Sequential forward reading means
the resultset maintains a cursor pointing to its
current row of data.
Initially the cursor is positioned before the 1st row.
The next() method moves the cursor forward to the
next row.
There is to move backward or update
the resultset and have the changes automatically
reflected in the database
NO WAY
36
4.0 Scrollable and Updateable ResultSet (Contd)
With JDBC 2, you can scroll the row both forward and
backward and move the cursor to a desired location.
You can also insert, delete or update a row in a result
set and have the changes automatically reflected in
the database.
37
4.0 Scrollable and Updateable ResultSet (Contd)
To obtain scrollable and updateable result set, you must
first create a statement with an appropriate type and
concurrency mode.
For a static Statement object, use
Statement stmt = connection.createStatement( int resultType,
int resultsetConcurrency);
For a preparedStatement object, use
PreparedStatement pstmt = connection.prepareStatement(
String sql, int resultType, int resultsetConcurrency);
38
4.0 Scrollable and Updateable ResultSet (Contd)
The value of resultType cound be:
resultType Possible values:
ResultSet.TYPE_FORWARD_ONLY
The result set is accessed forward sequential only

ResultSet.TYPE_SCROLL_INSENSITIVE
The result set is scrollable, but not sensitive to
changes in the database

ResultSet.TYPE_SCROLL_SENSITIVE
The result set is scrollable, and sensitive to
changes made by others
Use this type if you want to the result set to be
scrollable and updateable.
39
4.0 Scrollable and Updateable ResultSet (Contd)
The value of resultsetConcurrency cound be:
resultsetConcurrency
Possible values:
ResultSet.CONCUR_READ_ONLY
The result set CAN NOT be used to update
the database

ResultSet.CONCUR_UPDATABLE
The result set can be used to update the
database
Note:
UPDATABLE,
not
UPDATEABLE
40
4.0 Scrollable and Updateable ResultSet (Contd)
For example, if you want the result set to
be scrollable and updateable, you can
create a statement as follows:

Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Reminder Again:
UPDATABLE, not
UPDATEABLE
41
4.0 Scrollable and Updateable ResultSet (Contd)
After that, you can used the executeQuery() method
of the Statement object to execute an SQL query
that returns a result set, as follows:

ResultSet resultset = stmt.executeQuery(String sqlQuery);
42
4.0 Scrollable and Updateable ResultSet (Contd)
Then, you can use the various useful method in
ResultSet interface to scroll (move ) around result
or make changes to the resultset and have the
changes automatically reflected in the database
You can:
1. Scroll or move cursor around resultset
2. Retrieve value of a specified field in the current row
3. Delete the current row
4. Insert a new row ( means new record )
5. Update a particular row
43
4.0 Scrollable and Updateable ResultSet (Contd)
TO Scroll or move cursor around result set
Methods Description
first() Move cursor to the 1
st
row
next() Move cursor to the next row
previous() Move cursor to the previous row
last() Move cursor to the last row
absolute(int row) Move cursor to the specified row
Methods in ResultSet:
44
4.0 Scrollable and Updateable ResultSet (Contd)
TO Retrieve value of a specified field in the current row:

1. getXxx ( int columnIndex ) : Xxx
Retrieve the Xxx type value of a field specified by
columnIndex. [ field index starts from 1 ]

2. getXxx( String columnName ) : Xxx
Retrieve the Xxx type value of a field specified by
columnName.
[ same as field name in the database ]
The type Xxx could be String, int, double and etc..
45
4.0 Scrollable and Updateable ResultSet (Contd)
TO delete the current row in the result set
delete() Delete the current row in the result set,
changes will automatically reflected in
the database
46
4.0 Scrollable and Updateable ResultSet (Contd)
TO insert a new row in a resultset:

3 Steps to insert a row:
1. Call the moveToInsertRow() to move the cursor to a
special row that serves as a staging area for building a row
to be inserted.
2. Then, update the columns using the
updateXxx (int columnIndex, Xxx value) method or
updateXxx ( String columnName, Xxx value) method.

NOTE: Xxx = type of the value, for example: String, int,
double, and etc.
3. Finally, insert the row using the insertRow() method.
47
4.0 Scrollable and Updateable ResultSet (Contd)
For example, the following code insert a new row
with the new values:
// 1
st
, move cursor to the insert row ( MUST DO SO)
rsCustomer.moveToInsertRow();

// 2
nd
, update Cust_ID, Cust_Name & Cust_Address
rsCustomer.updateString(Cust_ID, C009);
rsCustomer.updateString(Cust_Name, Julia);
rsCustomer.updateString(Cust_Address, PJ);

// 3
rd
, just call the insertRow() method to insert new row
rsCustomer.insertRow();
48
4.0 Scrollable and Updateable ResultSet (Contd)
TO update a row in the result set

3 Steps to update a row
1. Move the cursor to desire row. You can use the
absolute(int row) method.
2. call the updateXxx() method to write new value
to the field at the current row
3. finally, call the updateRow() method to update
row in the data source
49
4.0 Scrollable and Updateable ResultSet (Contd)
For example, the code below updates the address of the
3rd row to Taman TBR
// move cursor to the 3rd row
rsCustomer.absolute(3);

// updates the columns
rsCustomer.updateString(Cust_Address, Taman
TBR);

// updates the row in the data source
rsCustomer.updateRow();
50
4.0 Scrollable and Updateable ResultSet (Contd)
Other useful method in the ResultSet interface:

cancelRowUpdates()
Cancels the updates made to a row
close()
Closes the result set and releases its resources
isFirst() : boolean
To check whether the cursor is at the 1st row in the
result set
isLast() : boolean
To check whether the cursor is at the last row in the
result set
51
4.0 Scrollable and Updateable ResultSet (Contd)
Other useful method in the ResultSet interface:

getRow(): int
Return the current row number.
The 1st row is 1, 2 for 2nd row and so on.
52
4.0 Scrollable and Updateable ResultSet (Contd)
Example 5:
Using Scrollable and Updateable Result Set

The program in Listing 4.4 below demonstrates
using scrollable and updateable result set to scroll
customer record and insert new customer record.
Run ViewCustomer ViewCustomer Code

You might also like