1.JDBC en
1.JDBC en
Information Repositories
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
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
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
12 of 77
Getting started
Development process
13 of 77
Execute a SQL instruction
Development process
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
16 of 77
Controlling ResultSet Fetch size
Development process
2
First column has index 1, not 0
18 of 77
Release resources
Development process
19 of 77
Error handling
Development process
■ Emtpy results
■ NULL values
■ ...
21 of 77
Error handling
Development process
22 of 77
Warnings
Development process
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
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
30 of 77
Statements
PreparedStatement
31 of 77
Statements
PreparedStatement main advantages
32 of 77
Statements
CallableStatement
33 of 77
Statements
Using CallableStatement
Stored procedure
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
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
41 of 77
Enhanced capabilities for ResultSet
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
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
47 of 77
Enhanced Result Sets
Performing a DELETE Operation in a Result Set
48 of 77
Enhanced Result Sets
Performing an UPDATE Operation in a Result Set
49 of 77
Enhanced Result Sets Examples
50 of 77
Enhanced Result Sets
Examples
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
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.
54 of 77
Enhanced Connections
DataSource lifecycle: Deploy DataSource object
55 of 77
Enhanced Connections
DataSource lifecycle: Using Deployed DataSource Object
56 of 77
Enhanced Connections
Advantages of DataSource Objects
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
61 of 77
Connection pools
Option when using JDBC connection pool
At run time,
■ the application requests a connection from a DataSource.
63 of 77
Connection pools examples
64 of 77
Using HSQLdb take a look to project HSQLdb-ConnectionPool and
run.
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
68 of 77
RowSet
Types of RowSet
69 of 77
RowSet. Classification
70 of 77
RowSet interfaces
JdbcRowSet
71 of 77
RowSet interfaces
CachedRowSet
72 of 77
RowSet interfaces
WebRowSet, JoinRowSet, FilteredRowSet
73 of 77
RowSet. Example
74 of 77
See an example in CachedRowSetTest project
75 of 77
Further Reading (1)
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