Web application with database
JDBC programming
Review
Objectives
Relational Database Overview
JDBC and JDBC Drivers
Steps to code JDBC CRUD task.
Database connection with data source
Statements and execution
JDBC transaction management
JDBC Enhancement
Database application design
Database and DBMS
Database is a collection of related data which are
stored in secondary mass storage and are used
by some processes concurrently.
Databases are organized in some ways in order
to reduce redundancies.
DBMS: Database management system is a
software which manages some databases. It
supports ways to users/processes for creating,
updating, manipulating on databases and
security mechanisms are supported also.
DBMS libraries (C/C++ codes are usually used)
support APIs for user programs to manipulate
databases.
Relational Database Overview
Common databases are designed and implemented
based on relational algebra (set theory).
Relational database is one that presents information
in tables with rows and columns.
A table is referred to as a relation in the sense that it
is a collection of objects of the same type (rows).
A Relational Database Management System
(RDBMS)- such as MS Access, MS SQL Server,
Oracle- handles the way data is stored, maintained,
and retrieved.
Structure Query Language (SQL)
Data Definition Language
(DDL): 3 languages:
CREATE…/ ALTER…/ DROP…
Data Manipulating
Language (DML):
SELECT…/ INSERT INTO
… / UPDATE … / DELETE
Data Control Language (DCL):
GRANT…/ REVOKE … / DENY…
Structure Query Language (SQL)
Common DML queries:
SELECT columns FROM tables WHERE condition
UPDATE table SET column=value,… Where condition
DELETE FROM table WHERE condition
INSERT INTO table Values ( val1, val2,…)
INSERT INTO table (col1, col2,…) Values ( val1, val2,…)
JDBC : Java Database Connectivity
JDBC is a technology standard consisting of
interfaces and classes that define how a Java
application connects and interacts with a
database..
The JDBC API is a Java API that can access any
kind of tabular data, especially data stored in a
Relational Database.
Connect to the database
Execute queries and update database
Retrieve the result received from the database.
JDBC Driver
The JDBC driver is an executable version of
JDBC developed by DBMS vendors that allows
Java applications to work with DBMSs.
Based on the characteristics of interaction with
DBMS, there are four types of JDBC drivers
Type 1: JDBC ODBC Bridge
Type 2: Native API
Type 3: Open Network Protocol
Type 4: Native Protocol
• Type 1 and Type 4 are populated.
Type 2-Driver: Native API
Provides access to the Application
database through C/C++ Java
codes. Application
Developed using native code
libraries
Native code libraries provide Type II JDBC
access to the database, and Driver
improve the performance
Java application sends a SQL Command Result Set
request for database
connectivity as a normal Native Database
JDBC call to the Native API Library
driver
Proprietary
Establishes the call, and Protocol
translates the call to the
particular database protocol Database
that is forwarded to the
database
Type 3: Open Network Protocol
Application
Use a pure Java client and
Java Application
communicate with a
middleware server using a
database-independent Type III JDBC
protocol. Driver
The middleware server then Result
communicates the client’s Set
Middleware
requests to the data source JDBC
Manages multiple Java
applications connecting to
different databases Database
Type 4-Driver: Native Protocol
Application
Communicates directly with the
Java Application
database using Java sockets
Improves the performance as
translation is not required
Converts JDBC queries into native Type IV JDBC
calls used by the particular Driver
RDBMS
The driver library is required when SQL command Result Set
it is used and attached with the
deployed application (sqlserver
2000: [Link], [Link], use Proprietary protocol
[Link]; sqlserver 2005:
[Link]; jtds: [Link] …) Database
Independent platform
Database URL
Database URL: string representing DBMS and database
addresses - specified by JDBC driver.
General syntax
jdbc:subprotocol name:other_stuff
subprotocol name: specified by the driver listed in the driver's
Database
manual. URL
Other_stuff: driver dependency
Ex
[Link](“[Link]”);
String dbURL=“jdbc:sqlserver://ServerName:Port;databaseName=FuLib”;
String user =“dbuserName”, pw=“xxxx”;
Connection con= [Link](dbURL,user, pw);
06/03/25 13
General introduction..
6 steps for JDBC database programming
Load JDBC driver
Create connection with database - DBMS
Generate SQL statement to perform desired task
Execute SQL statement
Processing execution results
Close connection
JDBC Driver can config to load by web server
or application server.
06/03/25 14
Loading Driver
DriverManager is a class that manages JDBC
drivers and creates connections with DBMS
[Link](String);
[Link](“[Link]”);
Equivalent to:
new [Link]();
or
[Link](new [Link]());
Can load multiple drivers simultaneously to interact with multiple
DBMS
Using Data Source without the need of loading driver
06/03/25 15
Make a connection
Depending on the DBMS the connection requires user
authentication
[Link](dbURL, user, password)
[Link](dbURL)
Connections to DBMS server is limited resources
Open connection when needed.
Close the connection immediately after finishing the task
Auto-close connection – use “try with resource” to
prevent leakage of connection resources (Java 8)
try(Connection con=[Link](…)){…}..
Connection Pool is a multi-user solution for database
applications with large user loads.
06/03/25 16
Configure Ports, Protocols for SQL Server…
Stop then restart SQL Server and SQL Server Agent for settings are
affected.
Righ
t
click
Review MVC
Step 3: Create &Execute a SQL statement
String sql1 = “SELECT columns FROM table1, table2, … WHERE condition”;
String sql2 = “UPDATE table SET column = value, … WHERE condition”;
String sql3 = “INSERT INTO table VALUES ( val1, val2, … )” ;
String sql4 = “INSERT INTO table (col1, col2, col3) VALUES ( val1, val2, val3)” ;
String sql5 = “UPDATE table SET col1 = ?, col2=? WHERE condition”;
// Connection con was created
Statement stmt= [Link]();
ResultSet rs= [Link](sql1);
int numOfInfectedRows = [Link](sql2);
int numOfInfectedRows = [Link](sql3);
int numOfInfectedRows = [Link](sql4);
PreparedStatement pStmt = [Link](sql5);
[Link] (index, val); // from 1
int numOfInfectedRows = [Link](); // no argument
Step 4: Process the results
BOF Move the current row:
boolean next(), previous(), first(), last()
Record 1
Default: Result set moves forward only.
Record 2
Record 3 Get data in columns of the current row:
TYPE getTYPE ( int columnIndex) // begin from 1
…..
TYPE getTYPE ( String columnLabel)
…..
….. SELECT desc AS description FROM T_employee
Column name: desc
EOF
Column Label: description
ResultSet
At a time, resultset maintains a current position. When the resultset is
initialized, the position is the BOF position. An exception is thrown
when the current position is out of its scope.
Step
Opening Order:
5: Close
Connection
the connection
Statement ResultSet
Closing Order: ResultSet Statement Connection
Attention!!!
At a time, a connection can be bound with ONLY ONE result set.
An exception will be thrown if we try binding a connection with another
result set.
EX:
String sql1 =“SELECT…”;
String sql2 =“SELECT…”;
ResultSet rs1= [Link](sql1);
ResultSet rs2= [Link](sql2); EXCEPTION
You should close the rs1 before trying get the rs2 result set
Solution: Transfer data in the rs1 to ArrayList (or Vector) then close rs1
before get new data to rs2.
Statement
Three types of Statement
Statement: execute arbitrary statements at run time
PreparedStatement : precompiled SQL statement
CallableStatement: call procedure on DBMS
Use the connection to create the statement
Statement s = [Link]();
PreparedStatement ps= [Link](String);
CallableStatement cs= [Link](String);
The Statement can be used many times for different
tasks, for any SQL
Statement <- PreparedStatement <- CallableStatement
06/03/25 25
PreparedStatement
Use PreparedStatement to increase SQL
statement execution efficiency
The SQL statement will be compiled once before
being called to execute multiple times.
Change the argument each time it's executed.
PreparedStatement updateAddr = [Link](
"UPDATE Customers SET Address = ? WHERE CustNo= ?");
[Link](1, “Danang”);
[Link](2,1001);
After setting the argument values, they are preserved
until a new value is set or a method is called
clearParameters() to clear the value of arguments
06/03/25 26
Execution of Statement
There are 3 ways of Statement execution.
executeQuery()
executeUpdate()
execute()
executeQuery()
used to execute queries
Select.. from ..where
Returns the query results via the ResultSet object.
ResultSet rs = [Link](“SELECT * FROM Books”);
06/03/25 27
Execute Statement..
executeUpdate()
used for the update data statement,
Returns the number of records affected by the UPDATE,
INSERT, or DELETE statement.
returns 0 , which means:
(1) no records are affected
(2) execute the data definition DDL statement.
execute()
when it is not clear whether the statement is a query or an
update.
used for dynamic SQL execution cases.,
returns true if the statement is a query.
call getResultSet() to get query result
call getUpdatedCount() to get the number of records updated.
06/03/25 28
ResultSet
ResultSet allows access to data returned from
database query results.
Retrieve each field of the record with a pointer to the
current position in the ResultSet
Call next( ) to move the current cursor to the next row
of the ResultSet.
next() returns true means there is data to read, otherwise: no
more row
use the following loop structure to traverse a ResultSet
while ([Link]()){
// manipulate row by row and column by column – forward only
}
06/03/25 29
Handling ResultSet..
The data at each field of the record is read by
method getType() :
type getType(int | String)
argument is column order – starting from 1- or column name
type of Type can be int, double, String, Date, .. arbitrary
String isbn = [Link](1); // Column 1
float price = [Link](“Price”);
Note
ResultSet associated with connection to database
Forward only by default
Automatic type conversion by JDBC driver
06/03/25 30
Make connection from DataSource
Declare data resource reference in [Link]
06/03/25 33
Make connection from DataSource
For web application, connection can create from Data
Source without loading driver when coding JDBC
Declare Data source in [Link]
06/03/25 34
Make connection from DataSource
Static method to create connection from data source
06/03/25 35
Callable Statement
CallableStatement provides a call to execute
pre-installed procedures on the DBMS.
Syntax
{Call procedure_name(arg1, arg2, ...)}
{?= call procedure-name arg1,arg2, ...}
Question mark ? substitute for arguments
The arguments can be input (IN parameters),
output (OUT parameters), or both (INOUT
parameters).
06/03/25 36
CallableStatement
CallableStatement cstmt = [Link]("{call
proc(?, ?)}");
Pass the IN argument using the setxxx() function that
inherits from PreparedStatement
Register the OUT argument before executing the
procedure
registerOutParameter(1,[Link]);
INOUT . argument
[Link](1,"00000");
[Link](1,[Link]);
Stored procedures are not suitable in a complex distributed
environment because they are tied to a particular DBMS
06/03/25 37
Transaction Management
Transaction: unit of work – all or nothing
By default, JDBC executes (commit) SQL statements once it is delivered to
the database; called autocommit mode
Some applications are transactional in nature - requiring execution tasks
either as a whole bundle or as doing nothing when error occur.
Turn off autocommit mode to perform transaction management
according to application characteristics
The Connection class provides the setAutoCommit() method to toggle
auto-commit mode on and off
The first sql statement also starts a transaction, ends with commit() or
rollback()
[Link](false);
s = [Link](); [Link](SQLString)
[Link]() ; or [Link]();
Note: Transaction is happening only within 1 connection
to the DBMS
06/03/25 38
Loading JDBC Driver - Establish connection to DB
Create & Execute SQL statement
String sql1 = “SELECT columns FROM table1, table2, … WHERE condition”;
String sql2 = “UPDATE table SET column = value, … WHERE condition”;
String sql3 = “INSERT INTO table VALUES ( val1, val2, … )” ;
String sql4 = “INSERT INTO table (col1, col2, col3) VALUES ( val1, val2, val3)” ;
String sql5 = “UPDATE table SET col1 = ?, col2=? WHERE condition”;
// Connection con was created
Statement stmt= [Link]();
ResultSet rs= [Link](sql1);
int numOfInfectedRows = [Link](sql2);
int numOfInfectedRows = [Link](sql3);
int numOfInfectedRows = [Link](sql4);
PreparedStatement pStmt = [Link](sql5);
[Link] (index, val); // from 1
int numOfInfectedRows = [Link](); // no argument
Process the results
BOF Move the current row:
boolean next(), previous(), first(), last()
Record 1
Default: ResultSet moves forward only.
Record 2
Record 3 Get data in columns of the current row:
TYPE getTYPE ( int columnIndex) // start from 1
…..
TYPE getTYPE ( String columnLabel)
…..
….. SELECT desc AS description FROM T_employee
Column name: desc
EOF
Column Label: description
ResultSet
At a time, resultset maintains a current position. When the resultset is
initialized, the position is at BOF position. An exception is thrown
when the current position is out of its scope.
Close connection - Release resource
Opening Order: Connection Statement ResultSet
Closing Order: ResultSet Statement Connection
Attention!!!
At a time, a connection can be bound with ONLY ONE result set.
An exception will be thrown if we try binding a connection with another result set.
EX:
String sql1 =“SELECT…”;
String sql2 =“SELECT…”;
ResultSet rs1= [Link](sql1);
ResultSet rs2= [Link](sql2); EXCEPTION
You should close the rs1 before trying get the rs2 result set
Solution: Transfer data in the rs1 to ArrayList (or Vector) then close rs1 before
get new data to rs2.
JDBC Enhancements
Two parts
Core Java feature enhancements. Print [Link] package
Extended features. Print [Link] package. Extra download
Enhancements
Scrollable Result Sets(in core API)
Batch Updates (in core API)
Advanced Data Types (in core API)
JNDI for connecting to a database (in extension API)
Connection pooling (in extension API)
Rowsets (an additional Result type) (print extension API)
Distributed transaction support (in extension API)
06/03/25 43
Scrollable Result Sets
ResultSet: three types of result sets
methods for moving the cursor to a particular row or to a relative
position (either forward or backward)
previous(), beforeFirst(), first(), last( ), absolute(),
and relative( ).
methods for ascertaining the current position of the cursor
constants indicating the scrollability of a result set
Connection
new versions of the methods for creating Statement,
PreparedStatement, and CallableStatement objects that make the
result sets that produce scrollable
[Link](
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
DatabaseMetaData
method indicating whether the DBMS and driver support scrollable
result sets
06/03/25 44
Batch Updates
The new batch update facility provides the ability to send
multiple updates to the database to be executed as a
batch rather than sending each update separately
Statement, PreparedStatement, and CallableStatement have
methods for adding update statements to a batch, clearing all
update statements, and executing a batch .
Statement s = [Link]();
[Link](“INSERT….“);
[Link](“INSERT….“);
[Link]();
can queue up SQL and execute in one call, improving efficiency
BatchUpdateException:
throw exception when an error occurs in a batch
update
06/03/25 45
Database application design
Multi-tier application structure allows to separate
the functionality of each layer, speeding up the
application development process
Creates relative independence of the business
object from the data layer: changing the DBMS or
database does not affect the business layer
Data Access Object (DAO) pattern is a structural
pattern that isolate the application/business layer
from the persistence layer using an abstract API.
Account – AccountDAO – AccountDB -> DBMS
(business obj) (interface) (implementation)
Practical exercise
Download and use a JDBC Driver from the
internet
Develop the Account class associated with the
Account table in the [Link] database
follow DAO pattern.
Pay attention to transaction management in multi-
step business tasks of Account
Combine error handling using Exception
Using Predicate and lambda expression for
searching account with different criteria
06/03/25 47
Summary
Introduction to databases
Relational Database Overview
JDBC and JDBC Drivers
Steps to develop a JDBC code.
Connection with data source
Statement and Execution
Transaction management
JDBC enhancement
Database application design