0% found this document useful (0 votes)
9 views77 pages

1.JDBC en

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views77 pages

1.JDBC en

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

JDBC

Information Repositories

School of Computer Science

2024-2025
Basic JDBC

2 of 77
JDBC1 definition
JDBC is a Java API to allow Java programs
to access a wide range of DBMS (relational
DB and other tabular data sources, such as
spreadsheets or flat files) by executing SQL
statements.
■ Consists of a set of interfaces and classes written in Java that

abstracts common database access functions to perform


connections with a database or other tabular data sources, sending
of SQL statements, processing of results, . . .
■ Database vendors provide implementations, called Driver.

□ Provides the connection with the DB


□ Convert java calls into db specific calls

1
It is not an acronym and thus stands for nothing but popular as Java
Database Connectivity
3 of 77
JDBC features
Database independence
JDBC interface provides a library of generic methods
■ Standard way to connect
■ Standard representation of data types
■ Standard set of error codes
The drivers provide different implementations and are loaded and
used at runtime on client-side.

4 of 77
JDBC features

Platform independence
JDBC drivers are developed in Java and there are drivers for (nearly)
any commercial DBMS
Object-relational mapping
Sets a virtual OODB over a RDBMS
The JDBC driver converts data types in the OOPL (Java) to the
appropriate database types. It uses a default mapping for most data
types.

5 of 77
JDBC architecture

Application Initiates and terminates connections, submits SQL


statements, . . . . Relies on JDBC (Java-based API)
To connect to a database, you need
JDBC vendor-specific drivers1 , a class
which implements java.sql.Driver
interface for this database (usually
com.dbProvider.jdbc.Driver) which
provides connection with a database and
converts Java calls into database
specific calls
Driver Manager loads appropriate driver during runtime
Data source processes SQL statements

1
Come in four varieties. For more information: [1]
6 of 77
Basic JDBC classes and interfaces

7 of 77
Development process

8 of 77
■ Import JDBC packages.
■ Load and register the JDBC driver.
■ Open a connection to the database.
■ Create a statement object to perform a query.
■ Execute the statement object and return a query resultset.
■ Process the resultset.
■ Close the resultset and statement objects.
■ Close the connection

9 of 77
Before connecting database: Load and register a
JDBC driver
Make the JDBC drivers available to your application
■ Download the appropriate drivers (in form of jar files)

□ From the IDE, add the .jar file to the project library
□ Copy .jar files to JAVA HOME /jre/lib/ext directory
□ Append location of .jar files to the CLASSPATH environment variable.
□ Run the application with the argument --classpath
■ Register JDBC Driver: This step causes the JVM to load the driver
implementation into memory so it can fulfill your JDBC requests.

10 of 77
Connect to the database
Development process

For stand-alone or desktop applications, use class DriverManager to


get an instance of a Connection object
Provide DriverManager with enough information to make connection

String url = ‘‘jdbc:mysql://localhost:1527/EmployeeDB’’;


String user = ‘‘username’’;
String pass = ‘‘s3cr3t’’;
Connection conn = DriverManager.getConnection
( url, user, pass );
11 of 77
Getting started
Development process

■ DriverManager will find appropriate


drivers when application requests a
Connection.
■ DriverManager getConnection and
getDrivers are enhanced to support
Service Provider mechanism.
■ JDBC 4.0 Drivers must include file
META-INF/services/java.sql.Driver
containing its implementation(s) of
java.sql.Driver

12 of 77
Getting started
Development process

■ When DriverManager first attempts to establish a connection, it


automatically loads any JDBC 4.0 drivers found within class
path[2]
■ When a driver is loaded, it automatically creates an instance of
itself and registers this instance with the DriverManager.
■ DriverManager will iterate over all registered drivers asking them
for a Connection. The driver will use the JDBC url to check if it’s
a protocol it supports (jdbc:mysql’).
■ Each one will return null (does not support the protocol) or an
established connection

13 of 77
Execute a SQL instruction
Development process

Statement interfaces abstract SQL statements and are primary


interface to tables in the DB (used to CRUD data from a table).
Create Statement objects as needed using database connection

Statement stmnt = conn.createStatement();

Executing the Statement object

14 of 77
Get the results
Development process

The set of rows selected from the database in a query are virtually
returned in an object which implements java.sql.ResultSet.
■ Grants access to tables generated as results of executing a stmnt

■ Only one ResultSet per Statement can be open at the same time!

15 of 77
Get the results
Development process

Application-level cursor pointing to current row.


■ When created, it is positioned before the first row.
■ By default, rows are retrieved in sequence: next() moves the
cursor to next row and returns a boolean indicating whether or not
another record exists.

16 of 77
Controlling ResultSet Fetch size
Development process

■ Data returned by query isn’t usually stored in the ResultSet object


but remains on DB server
■ When is a row read from the server and cached by the ResultSet?
■ How can we run queries that return a much larger volume of data
than can be cached in machines memory?
■ The number of rows returned on a single database round trip is
determined by the JDBC driver: Fetch size
rs.setFetchSize(25);
Calls to rx.next() return the data in
the cache until the 26th row, at wich
time the driver will fetch another 25
rows.
17 of 77
Collection of methods for reading data
Development process

■ getXXX (String fieldName) getXXX (int columnIndex2 )


□ getInt(), getLong(), getString()
□ ResultSet contains SQL datatypes
□ Return the value of the field name or column index, for current record
in the result set, formatted to an specific datatype of host language

2
First column has index 1, not 0
18 of 77
Release resources
Development process

19 of 77
Error handling
Development process

Hundreds of potential problems


■ No database connection or connection timeout

■ Wrong login or missing privileges

■ SQL syntax errors

■ Emtpy results

■ NULL values

■ ...

1. Hence always check database return values


2. Provide error handling code, exception handlers
3. Gracefully react to errors or empty results or NULL values
4. NEVER show database errors to end users
□ Not only bad user experience, but huge security risk, . . .
20 of 77
Error handling
Development process

1. What errors may be raised during driver loading?


ClassNotFoundException
2. Errors raised during database access: SQLException
It is a checked exception so we must either catch it or throw it.

21 of 77
Error handling
Development process

3. Handling NULLs: SQL’s NULL different concept than Java’s null.


To detect and handle NULL’s
3.1 Avoid using getXXX( ) methods that return primitive data types.
NullsTactics-Tactic1
3.2 Use wrapper classes for primitive data types and wasNull().
NullsTactics-Tactic2
3.3 Use primitive data types and wasNull(). NullsTactics-Tactic3
Some useful methods to process exceptions:
■ int getErrorCode()
■ String getSQLState()
■ void setNextException(SQLException ex), SQLException
getNextException()

22 of 77
Warnings
Development process

■ Warnings do not stop execution of application, as exceptions do


■ getWarnings() reported by Connection, ResultSet and Statement
objects
□ DataTruncation: problem with reading or writing data.
■ clearWarning() clear all the warnings reported

23 of 77
Putting it all together
Development process

24 of 77
Exercise

25 of 77
Exercise: CarWorkshop database
Assume HSQLDB CarWorkshop running in the local computer.
After this exercise, the next several tasks should be familiar
■ Connect to the database
■ Write a query to read table tvehicles.
TVEHICLES(ID BIGINT NOT NULL PRIMARY KEY, BRAND
VARCHAR(255) NOT NULL, MODEL VARCHAR(255) NOT NULL,
PLATENUMBER VARCHAR(255) NOT NULL, CLIENT ID BIGINT,
VEHICLETYPE ID BIGINT)
■ Execute the query and get the results.
■ Print the results.
□ Print just plate number, owner id, brand and model and vehicle type.
□ Be careful with NULLs (no owner registered, no brand registered, . . . )
■ Release the resources.
26 of 77
Statements. Advanced Concepts

27 of 77
Statements
Lifecycle

When one of Statement’s execute() methods is called


1. Statement object submits the SQL statement to the database
2. Database compiles the given SQL statement
□ Parsing SQL string, often longer than time required to run the query
□ Checking the syntax.
□ Checking the semantics.
3. Database prepares execution plan to execute SQL statement
□ Query optimizer evaluates some different plans for executing the query
and returns what it considers best alternative.
□ Not necessary to be done each time
□ DBMSs are designed to store the execution plans and execute them
multiple times if required. Pre-compiled SQL statements.

28 of 77
4. Execution plan for compiled SQL statement is then executed.
5. Now, if the SQL statement retrieves data (SELECT), database
caches results into buffer.
6. Results are sent to Statement object
7. Finally, response is sent to the Java application in the form of
ResultSet.

29 of 77
Statements
Interfaces

■ Statement: Used to execute normal SQL queries.


□ Can’t pass parameters to SQL query at run time using it.
□ Preferred when executing a SQL query only once. Poor performance
otherwise.
■ PreparedStatement: Used to execute dynamic or parameterized
SQL queries.
□ It extends Statement interface.
□ Can pass parameters to SQL query at run time.
□ Recommended if a particular SQL query is being executed multiple
times. DBMS caches execution plan. Better performance.
■ CallableStatement: Used to execute stored procedures. It
extends PreparedStatement.

30 of 77
Statements
PreparedStatement

■ Instead of hardcoding SQL values (col = 1), use placeholder (?)


String sql = ‘‘UPDATE table SET col1 = ?
WHERE col2 = ? AND col3 = ?’’;
PreparedStatement pst = conn.prepareStatement( sql );
■ Set values to all the bind variablesbefore executing the statement
pst.setString(1,fooValue1);
pst.setInt(2,fooValue1);
pst.setWhatever(3,fooValue3);
■ Can be used for select, insert, update and delete.
■ Only no-parameters versions of executeUpdate() and
executeQuery() allowed with prepared statements.

31 of 77
Statements
PreparedStatement main advantages

1. Create parameterized statements such that data for parameters


can be dynamically substituted is easier
2. Prevent against dependency injection attacks by allowing data
values may not be character strings
3. Precompiling SQL statements may improve performance by
avoiding repeated compiling of the same SQL statement

32 of 77
Statements
CallableStatement

Stored procedure is a set of SQL statements that perform a


particular task, take parameters (IN, OUT, INOUT) and return result
sets or discrete values in OUT or INOUT parameters.
To call stored procedures from Java
CallableStatement mycall = conn.prepareCall
("{call procedure_name}");
("{call procedure_name(?, ?,...)}");
("{? = call function_name}");
("{? call function_name(?, ?, ...)}");

33 of 77
Statements
Using CallableStatement

Stored procedure

create procedure getAvgSalary


( IN dept varchar(64), OUT avgSalary decimal (10,2))
begin
select avg(salary) into avgSalary
from employees
where department = dept
end

34 of 77
Statements
Using CallableStatement

Java code
// Prepare callable statement
CallableStatement myCall = conn.prepareCall
("{call getAvgSalary(?, ?)}");
// Set parameter
mycall.setString(1, "Human Resources");
mycall.registerOutParameter(2, Types.DOUBLE);
// Execute call
myCall.execute();
// Get result
System.out.println("Average salary: "
+ myCall.getDouble(2));

35 of 77
Statements
Using CallableStatement

Another example (java code)

CallableStatement call = conn.prepareCall(


"{CALL doubleMyInt(?)}");
// for inout parameters, it is good practice to register
// the out parameter before setting the input value
call.registerOutParameter(1, Types.INTEGER);
call.setInt(1,10);
call.execute();
int retval = call.getInt(1);

36 of 77
Summary

37 of 77
Exercises

38 of 77
1. Consider CarWorkshop database.
2. Write and execute a query to return the id of any client in Oviedo.
3. Using previous identifiers, write and execute a second query to
return plate numbers of any vehicle owned by them.

39 of 77
Enhanced ResultSet

40 of 77
Enhanced ResultSet in JDBC 2.0

Connection object’s createStatement() method is overloaded:

Statement createStatement(int rsType, int


rsConcurrency)

rsType determines scrollability, positioning and sensitivity

rsConcurrency determines updatability.

Adding these capabilities may cause additional overhead.

For further information read carefully[3]

41 of 77
Enhanced capabilities for ResultSet

■ sensitivity, ResultSet is aware of changes made by others (from


outside the enclosing Tx) to underlying data. It presumes the Tx
itself has an isolation level setting that allows changes to be visible.
■ scrollability and positioning, cursor can move in both directions
and can be positioned in a particular row
■ updatability, ResultSet can be updated with its update methods.

42 of 77
Enhanced Result Sets
Based on the capabilities of scrollability and sensitivity to changes

Constant Description
Not scrollable, not positionable, and not sensi-
TYPE FORWARD ONLY
tive.
Scrollable, positionable, and not sensitive
TYPE SCROLL INSENSITIVE (unless the program queries the database
again).
TYPE SCROLL SENSITIVE Scrollable, positionable, and sensitive.

43 of 77
Enhanced Result Sets
Based on the update capabilities

Constant Description
Specifies that a ResultSet cannot be updated
(i.e., changes to the ResultSet contents cannot
CONCUR READ ONLY
be reflected in the database with ResultSet ’s
update methods).
Specifies that a ResultSet can be updated (i.e.,
CONCUR UPDATABLE changes to its contents can be reflected in the
database with ResultSet ’s update methods).
You can find an example here https:
//examples.javacodegeeks.com/core-java/sql/updatable-resultset-example/

44 of 77
Enhanced Result Sets
Result Set Limitations and Downgrade Rules

To produce an updatable result set:


■ A query can select from only a single table and cannot contain join
operations.
■ For inserts to be feasible, query must select all non-nullable
columns and all columns that do not have a default value.
■ It cannot use SELECT * (there is a workaround for this).
■ It must select table columns only (cannot select derived columns or
aggregates, such as the SUM or MAX of a set of columns).
To produce a scroll-sensitive result set:
■ A query cannot use SELECT * (there is a workaround for this).
■ A query can select from only a single table.

45 of 77
Enhanced ResultSet
Summary of Visibility of Internal and External Changes

Can a result set object (in the Oracle JDBC implementation) see
changes made
■ internally through the result set itself ?
■ changes made externally to the underlying database from elsewhere
in your transaction or from other committed transactions? Careful
here. Read about fetch-size and window concepts in [3]

Result Set Type Can see Can see Can see Can see Can see Can see
internal internal UP- internal external external UP- external
DELETE? DATE? INSERT? DELETE? DATE? INSERT?
forward-only no yes no no no no
scroll-sensitive yes yes no no yes no
scroll-insensitive yes yes no no no no

46 of 77
Enhanced Result Sets
Performing an INSERT Operation in a Result Set

ResultSet interface offers methods to change the ResultSet but it


must be updatable.
1. moveToInsertRow() places the cursor in the insert-row, an area
that holds data for the inserted row until it is copied to database.
2. updateXXX() allows you to write data to the columns
rs.updateInt(1, integerValue);
rs.updateString(2, "stringValue");
3. insertRow() inserts the insert-row to ResultSet and to the table
as well. Permanent with next transaction COMMIT operation.
Positioning to a different row (moveToCurrentRow()) before calling
insertRow cancels the insert and clears the insert-row.

47 of 77
Enhanced Result Sets
Performing a DELETE Operation in a Result Set

ResultSet must be updatable.


1. Set the cursor to a selected row using one of the positioning
methods in the ResultSet object.
2. Delete the row using void deleteRow(). It deletes current row
from ResultSet object and from the underlying database; it cannot
be called when the cursor is on the insert row.
3. To make sure that the deleted row operation will be reflected in
the resultSet you must refresh the resultSet with a
ResultSet.close() and then create a new ResultSet with the
Statement.executeQuery() method.

48 of 77
Enhanced Result Sets
Performing an UPDATE Operation in a Result Set

ResultSet must be updatable.


1. Set the cursor to a selected row.
2. Update column data using updateXXX(num/name, type) that
updates a type object in the column with number num or name.
3. When you have updated the columns as required, you must use
void updateRow() to update the database table. This method
cannot be called when the cursor is on the insert row.
4. If you may decide that you don’t want to update the row, you can
call the void cancelRowUpdates() method instead.

49 of 77
Enhanced Result Sets Examples

50 of 77
Enhanced Result Sets
Examples

Run the following projects and check what happens.


1. Ex3-ResultSet-Scrollability
2. Ex3-ResultSet-Sensitivity
□ Choose option 8 (update + sensitive + external). Run. From
SQLDeveloper change first and last row and continue.
□ Uncomment line 16 from Sensitive.java. Run again.
□ Choose option 8 (update + sensitive + external). Run. From
SQLDeveloper change first and last row and continue.
□ Redo with ojdbc6 and ojdbc8. Notice differences.
Next, there are slides with details about operations in ResultSet

51 of 77
Enhanced connections

52 of 77
Enhanced Connections
Before you can read or write data from and to a resource (usually
a relational database) via JDBC, you need to open a connection
to it: java.sql.Connection.
■ Use DriverManager.getConnection(...) for stand-alone or

desktop applications.
□ Needs a driver- and database-specific URL so it causes your
application to be tightly coupled to a specific driver and database.
■ DataSource interface that provides a fully decoupled way for
JDBC clients to obtain a DBMS connection.
□ From JDBC 2.x
□ For further information, read [5]

53 of 77
Enhanced Connections

Data sources are standard, general-use objects for specifying


databases or other resources to use.

They have properties that determine the identity of the data source
and the way the data is handled on a database connection. This
properties can be modified when necessary.

For example, if the data source is moved to a different server, the


property for the server can be changed.

54 of 77
Enhanced Connections
DataSource lifecycle: Deploy DataSource object

55 of 77
Enhanced Connections
DataSource lifecycle: Using Deployed DataSource Object

Applications can use logical names in accessing services, removing


vendor-specific syntax from application code. Increase portability.

56 of 77
Enhanced Connections
Advantages of DataSource Objects

Using DataSource objects for getting a connection


■ client applications become more portable because driver name or
JDBC URL are no longer hardcoded.
■ simpler code so easier to maintain. Changes affect only to
DataSource properties, not to client code.
■ DataSource interface implemented to work with
ConnectionPoolDataSource, will produce pooled connections
automatically.

57 of 77
Enhanced Connections Example

58 of 77
Review these projects.
1. NO JNDI-DataSource-Oracle
2. Using rmiregistry, JNDI-DataSource-Client and
JNDI-DataSource-Server
Notice the differences between 1 and 2.
For more information, read[6]

59 of 77
Connection pooling

60 of 77
Connection pools

As getting and maintaining connections is expensive, connection


pooling is a common practice.

A connection pool is a cache of database connection objects.


The objects represent physical database connections that can be
reused whenever a request comes to connect with the database.

So, it reduces database hits and improves the application performance


significantly.

61 of 77
Connection pools
Option when using JDBC connection pool

1. Application server supports this feature. It creates the connection


pool on behalf of developers when it starts. Developers need to
give properties like min, max and incremental sizes to the
application server.
2. Developers can use JDBC 2.0 interfaces, for e.g.
ConnectionPoolDataSource and PooledConnection if the
driver implements these interfaces.
3. Developers can even create their own connection pool or use a
third party if they are not using any application server or JDBC 2.0
compatible driver.
□ OracleConnectionCacheManager (only for Oracle)
□ c3p0
□ BoneCP
□ Jakarta DBCP
62 of 77
Connection pools

At run time,
■ the application requests a connection from a DataSource.

□ If the pool contains a connection that can satisfy the request, it


returns the connection to the application.
□ If no connections are found, a new connection is created and returned
to the application.
■ when the application finishes, it returns the connection object
back to the pool. The connection is then available for the next
connection request.

63 of 77
Connection pools examples

64 of 77
Using HSQLdb take a look to project HSQLdb-ConnectionPool and
run.

Notice the time spent in each execution

Try to repeat with Oracle. What happens? Can you imagine why?

65 of 77
RowSet

66 of 77
RowSet
RowSet extends ResultSet and therefore share its capabilities.
What makes RowSet objects special is that they add new capabilities

■ Scrollable and updatable by default.


■ Far more adaptable and simpler to use than a ResultSet.
■ It is an in-memory copy of data held in the DB so it can update
in-memory data and update DB later (acceptChanges(), . . . )
■ Function as JavaBeans Component, so [disconected] can be
serialized and sent through the network.
RowSet can be provided by JDBC driver or third parties can
implement the specification by providing different layers of ResultSet
encapsulation.
Read [7] for more info
67 of 77
Row sets
ResultSet and RowSet. Major points of difference

68 of 77
RowSet
Types of RowSet

Depending on the duration of their connection to the database.

■ A connected RowSet establishes a connection to the DB that is


maintained throughout the lifespan of the RowSet object

■ A disconnected RowSet connects to read or write and, after


completion, it disconnects from the datasource.
□ Data can be changed while it is disconnected.
□ Modified data can be updated later to the database after a
disconnected Rowset reestablishes the connection with the database.

69 of 77
RowSet. Classification

70 of 77
RowSet interfaces
JdbcRowSet

It is an enhanced and extended ResultSet


There are different way to create a JdbcRowSet [8]

A complete example in [9]

71 of 77
RowSet interfaces
CachedRowSet

Disconnected rowset; it caches its data in memory (paging


available).
It is also serializable, so it can be passed between Java applications
through a network.
Not suitable for very large data sets, but an ideal way to provide thin
clients (PDA, ...).

72 of 77
RowSet interfaces
WebRowSet, JoinRowSet, FilteredRowSet

■ The WebRowSet interface extends the CachedRowSet interface


and therefore has all of the same capabilities. What it adds is the
ability to read and write a rowset in XML format.
■ JoinRowSet extends WebRowSet. A JoinRowSet object lets a
programmer combine data from two different RowSet objects. This
can be especially valuable when related data is stored in different
data sources.
■ FilteredRowSet interface also extends WebRowSet. A
FilteredRowSet object lets a programmer use a filtered subset of
data from a rowset. Something similar to WHERE.
This filtering is done by the method next, which is implemented to
skip any rows that do not fall within the specified range.

73 of 77
RowSet. Example

74 of 77
See an example in CachedRowSetTest project

75 of 77
Further Reading (1)

[1] https://en.wikipedia.org/wiki/JDBC driver


[2] https://www.tutorialspoint.com/jdbc/jdbc-db-
connections.htm
[3] https://docs.oracle.com/cd/B19306 01/java.102/
b14355/resltset.htm
[4] https://docs.oracle.com/cd/A84870 01/doc/
java.816/a81354/resltse7.htm
[5] Read Oracle Database JDBC Developer’s Guide and Reference,
chapter 8
[6] https://docs.oracle.com/javase/tutorial/jdbc/
basics/sqldatasources.html

76 of 77
Further Reading (2)

[7] https://docs.oracle.com/javase/tutorial/
jdbc/basics/rowset.html
[8] https://docs.oracle.com/javase/tutorial/jdbc/
basics/jdbcrowset.html#creating-jdbcrowset-object
[9] https://examples.javacodegeeks.com/enterprise-
java/sql-enterprise-java/javax-sql-rowset-
jdbcrowset-example/

77 of 77

You might also like