4. JDBC – Java Database Connectivity
JDBC is a standard interface for connecting to
relational databases from Java.
The JDBC classes and interfaces are in the java.sql
package.
JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of
Java 2
4 viska@unsyiah.ac.id
5. Apakah itu JDBC?
JDBC provides Java applications with access to
most database systems via SQL
The architecture and API closely resemble
Microsoft's ODBC
JDBC 1.0 was originally introduced into Java 1.1
JDBC 2.0 was added to Java 1.2
JDBC is based on SQL-92
JDBC classes are contained within the java.sql
package
There are few classes
There are several interfaces
5 viska@unsyiah.ac.id
6. Database connectivity history
Before APIs like JDBC and ODBC, database
connectivity was tedious
Each database vendor provided a function library for
accessing their database
The connectivity library was proprietary.
If the database vendor changed for the application, the
data access portions had to be rewritten
If the application was poorly structured, rewriting its data
access might involve rewriting the majority of the
application
The costs incurred generally meant that application
developers were stuck with a particular database product
for a given application
6 viska@unsyiah.ac.id
7. Arsitektur JDBC
With JDBC, the application programmer uses the
JDBC API
The developer never uses any proprietary APIs
• Any proprietary APIs are implemented by a JDBC
driver
• There are 4 types of JDBC Drivers
Java Application
JDBC API
JDBC DriverManager
JDBC Driver JDBC Driver
7 viska@unsyiah.ac.id
9. JDBC Drivers
There are 4 types of JDBC Drivers:
Type 1 - JDBC-ODBC Bridge
Type 2 - JDBC-Native Bridge
Type 3 - JDBC-Net Bridge
Type 4 - Direct JDBC Driver
Type 1 only runs on platforms where ODBC is available
ODBC must be configured separately
Type 2 Drivers map between a proprietary Database API
and the JDBC API
Type 3 Drivers are used with middleware products
Type 4 Drivers are written in Java
In most cases, type 4 drivers are preferred
9 viska@unsyiah.ac.id
11. Type 1: JDBC-ODBC Bridge Driver
This is an approach wherein the implemented class in Java makes
calls to the code written in Microsoft languages (native), which
speaks directly to the database.
The first category of JDBC drivers provides a bridge between the
JDBC and the ODBC API . The bridge translates the standard JDBC
calls and sends them to the ODBC data source via ODBC libraries .
Type 1 drivers use a bridge technology to connect a Java client to an
ODBC database system. The JDBC-ODBC Bridge from Sun and
InterSolv is the only extant example of a Type 1 driver. Type 1 drivers
require some sort of non-Java software to be installed on the
machine running your code, and they are implemented using native
code.
11 viska@unsyiah.ac.id
12. Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls
which are unique to the database. These drivers typically provided by the
database vendors and used in the same manner as the JDBC-ODBC Bridge,
the vendor-specific driver must be installed on each client machine.
This is an approach wherein the implemented class in Java makes calls to
the code written from the database provider (native), which speaks directly to
the database.
If we change the Database we have to change the native API as it is specific
to a database and they are mostly obsolete now but you may realize some
speed increase with a Type 2 driver, because it eliminates ODBC's
overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
12 viska@unsyiah.ac.id
13. Type 3: JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to accessing databases. The
JDBC clients use standard network sockets to communicate with an
middleware application server. The socket information is then translated by
the middleware application server into the call format required by the DBMS,
and forwarded to the database server.
You can think of the application server as a JDBC "proxy," meaning that it
makes calls for the client application. As a result, you need some knowledge
of the application server's configuration in order to effectively use this driver
type.
The Java client application sends a JDBC calls through a JDBC driver to the
intermediate data access server ,which completes the request to the data
source using another driver . This driver uses a database independent
protocol , to communicate database request to a server component which
then translate the request into a DB specific protocol .
13 viska@unsyiah.ac.id
14. Type 4: 100% pure Java
In a Type 4 driver, a pure Java-based driver that communicates directly with
vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by the
vendor itself.
This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
This is an approach wherein the implemented class in Java (implemented by
the database provider) speaks directly to the database. In other words , it is
a pure Java library that translates JDBC request directly to a Database
specific protocol .
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4
drivers.
14 viska@unsyiah.ac.id
15. So which driver?
If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is
4.
If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
Type 2 drivers are useful in situations where a type 3
or type 4 driver is not available yet for your
database.
The type 1 driver is not considered a deployment-
level driver and is typically used for development and
testing purposes only.
15 viska@unsyiah.ac.id
18. JDBC Classes
DriverManager
Manages JDBC Drivers
Used to Obtain a connection to a Database
Types
Defines constants which identify SQL types
Date
Used to Map between java.util.Date and the SQL DATE type
Time
Used to Map between java.util.Date and the SQL TIME type
TimeStamp
Used to Map between java.util.Date and the SQL TIMESTAMP
type
18 viska@unsyiah.ac.id
19. JDBC Interfaces
Driver
All JDBC Drivers must implement the Driver interface.
Used to obtain a connection to a specific database type
Connection
Represents a connection to a specific database
Used for creating statements
Used for managing database transactions
Used for accessing stored procedures
Used for creating callable statements
Statement
Used for executing SQL statements against the database
19 viska@unsyiah.ac.id
20. JDBC Interfaces
ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting data
PreparedStatement
Similar to a stored procedure
An SQL statement (which can contain parameters) is compiled
and stored in the database
CallableStatement
Used for executing stored procedures
DatabaseMetaData
Provides access to a database's system catalogue
ResultSetMetaData
Provides information about the data contained within a
ResultSet
20 viska@unsyiah.ac.id
22. Using JDBC
To execute a statement against a database, the following flow is
observed
Load the driver (Only performed once)
Obtain a Connection to the database (Save for later use)
Obtain a Statement object from the Connection
Use the Statement object to execute SQL. Updates, inserts and deletes
return Boolean. Selects return a ResultSet
Navigate ResultSet, using data as required
Close ResultSet
Close Statement
Do NOT close the connection
The same connection object can be used to create further statements
A Connection may only have one active Statement at a time. Do not
forget to close the statement when it is no longer needed.
Close the connection when you no longer need to access the database
22 viska@unsyiah.ac.id
25. Is an interpreter that translates JDBC method calls to
vendor-specific database commands
Implements interfaces in java.sql
Can also provide a vendor’s extensions to the JDBC
standard
Driver
JDBC calls
Database
commands
Database
A JDBC Driver
25 viska@unsyiah.ac.id
26. About JDBC URLs
JDBC uses a URL to identify the database
connection.
jdbc:<subprotocol>:<subname>
Protocol
Database
identifier
jdbc:oracle:<driver>:@<database>
Subprotocol
26 viska@unsyiah.ac.id
28. Thin driver
OCI driver
Server-side driver: Use the default connection
jdbc:oracle:thin:@<host>:<port>:<SID>
jdbc:oracle:oci8:@<TNSNAMES entry>
JDBC URLs with Oracle Drivers
28 viska@unsyiah.ac.id
29. Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection
(URL, userid, password);
ConnectionConnection connconn ==
DriverManager.getConnectionDriverManager.getConnection("("jdbc:mysqljdbc:mysql://://locloc
alhostalhost/books", "root", "/books", "root", "mysqlmysql");");
2. Connect to the database.
How to Make the Connection
1. Register the driver.
29 viska@unsyiah.ac.id
30. Using Connection
java.sql.Connection Creating Statement
Transaction Management
Get database metadata
Connection related
createStatement()
prepareStatement(String)
prepareCall(String)
commit()
rollback()
getMetaData()
close()
isClosed()
30 viska@unsyiah.ac.id
32. The Statement Object
A Statement object sends your SQL statement to the
database.
You need an active connection to create a JDBC
statement.
Statement has three methods to execute a SQL
statement:
executeQuery() for QUERY statements
executeUpdate() for INSERT, UPDATE, DELETE, or
DDL statements
execute() for either type of statement
32 viska@unsyiah.ac.id
33. 1. Create an empty statement object.
2. Execute the statement.
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
How to Query the Database
33 viska@unsyiah.ac.id
34. Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS
where rental_id = 1011");
Querying the Database: Examples
Execute a select statement.
• Execute a delete statement.
34 viska@unsyiah.ac.id
35. Close
Query
Step through the results
Process
results
Assign results to Java
variables
Connect
Stage 3: Process the Results
35 viska@unsyiah.ac.id
36. The ResultSet Object
JDBC returns the results of a query in a ResultSet
object.
A ResultSet maintains a cursor pointing to its current
row of data.
Use next() to step through the result set row by row.
getString(), getInt(), and so on assign each value to
a Java variable.
36 viska@unsyiah.ac.id
37. while (rset.next()) { … }
String val =
rset.getString(colname);
while (rset.next()) {
String title = rset.getString("TITLE");
String year = rset.getString("YEAR");
… // Process or display the data
}
String val =
rset.getString(colIndex);
How to Process the Results
1. Step through the result set.
2. Use getXXX() to get each column value.
37 viska@unsyiah.ac.id
38. while (rset.next()) {
String year = rset.getString("YEAR");
if (rset.wasNull() {
… // Handle null value
}
…}
How to Handle SQL Null Values
Java primitive types cannot have null values.
Do not use a primitive type when your query
might return a SQL null.
Use ResultSet.wasNull() to determine whether a
column has a null value.
38 viska@unsyiah.ac.id
39. Mapping Database Types to Java Types
ResultSet maps database types to Java types.
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, RENTAL_DATE, STATUS
from ACME_RENTALS");
int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);
Col Name
RENTAL_ID
RENTAL_DATE
STATUS
Type
NUMBER
DATE
VARCHAR239 viska@unsyiah.ac.id
40. SQL Types/Java Types Mapping
SQL Type Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
40 viska@unsyiah.ac.id
42. 1. Close the ResultSet object.
2. Close the Statement object.
3. Close the connection (not necessary for server-side
driver).
rset.close();
stmt.close();
conn.close();
How to Close the Connection
42 viska@unsyiah.ac.id
46. The DatabaseMetaData Object
The Connection object can be used to get a
DatabaseMetaData object.
This object provides more than 100 methods to
obtain information about the database.
46 viska@unsyiah.ac.id
47. 1. Get the DatabaseMetaData object.
2. Use the object’s methods to get the metadata.
DatabaseMetaData dbmd = conn.getMetaData();
String s1 = dbmd getURL();
String s2 = dbmd.getSQLKeywords();
boolean b1 = dbmd.supportsTransactions();
boolean b2 = dbmd.supportsSelectForUpdate();
How to Obtain Database Metadata
DatabaseMetaData dbmd = conn.getMetaData();
47 viska@unsyiah.ac.id
48. The ResultSetMetaData Object
The ResultSet object can be used to get a
ResultSetMetaData object.
ResultSetMetaData object provides metadata,
including:
Number of columns in the result set
Column type
Column name
48 viska@unsyiah.ac.id
49. How to Obtain Result Set Metadata
1. Get the ResultSetMetaData object.
2. Use the object’s methods to get the metadata.
ResultSetMetaData rsmd = rset.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++)
{
String colname = rsmd.getColumnName(i);
int coltype = rsmd.getColumnType(i);
…
}
ResultSetMetaData rsmd = rset.getMetaData();
49 viska@unsyiah.ac.id
50. The PreparedStatement Object
A PreparedStatement object
holds precompiled SQL statements.
Use this object for statements you want to execute
more than once.
A prepared statement can contain variables that you
supply each time you execute the statement.
50 viska@unsyiah.ac.id
51. How to Create a Prepared Statement
1.Register the driver and create the database
connection.
2.Create the prepared statement, identifying variables
with a question mark (?).
PreparedStatement pstmt =
conn.prepareStatement("update ACME_RENTALS
set STATUS = ? where RENTAL_ID = ?");
PreparedStatement pstmt =
conn.prepareStatement("select STATUS from
ACME_RENTALS where RENTAL_ID = ?");
51 viska@unsyiah.ac.id
52. How to Execute a Prepared Statement
1. Supply values for the variables.
2. Execute the statement.
pstmt.setXXX(index, value);
pstmt.executeQuery();
pstmt.executeUpdate();
PreparedStatement pstmt =
conn.prepareStatement("update ACME_RENTALS
set STATUS = ? where RENTAL_ID = ?");
pstmt.setString(1, "OUT");
pstmt.setInt(2, rentalid);
pstmt.executeUpdate();
52 viska@unsyiah.ac.id
53. The CallableStatement Object
A CallableStatement object holds parameters for
calling stored procedures.
A callable statement can contain variables that you
supply each time you execute the call.
When the stored procedure returns, computed
values (if any) are retrieved through the
CallabableStatement object.
53 viska@unsyiah.ac.id
54. Register the driver and create the database
connection.
Create the callable statement, identifying variables
with a question mark (?).
CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM + "(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);
How to Create a Callable Statement
54 viska@unsyiah.ac.id
55. 1. Set the input parameters.
2. Execute the statement.
3. Get the output parameters.
How to Execute a Callable Statement
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
55 viska@unsyiah.ac.id
56. Using Transactions
The server-side driver does not support autocommit
mode.
With other drivers:
New connections are in autocommit mode.
Use conn.setAutoCommit(false) to turn autocommit
off.
To control transactions when you are not in
autocommit mode:
conn.commit(): Commit a transaction
conn.rollback(): Roll back a transaction
56 viska@unsyiah.ac.id