3. June 21, 2017 3
JDBC
• JDBC is an API for the Java programming language that
defines how a client may access a database. It provides
methods for querying and updating data in a database.
• JDBC
- is the Java object version of Microsoft ODBC.
- defines Java class wrappers for SQL database access.
- can access almost any database service.
- JDBC drivers are available from almost any Java vendor.
- java.sql.* package is now part of the Java core.
- compliance means the drivers support SQL92.
- must implement the java.sql.* classes.
- must be thread safe.
4. • JDBC Naming Convention.
"jdbc:oracle:thin:@oracle-prod:1521:OPROD“ , "scott", "tiger”
The first string is the URL for the database including the
protocol (jdbc), the vendor (oracle), the driver (thin), the
server (oracle-prod), the port number (1521), and a
server instance (OPROD).
Second is the Username.
Third is the Password.
• JDBC Classes
– JDBC Core Interfaces
– Java Language extensions
– Java Utility Extensions
– SQL Metadata Interfaces.
June 21, 2017 4
JDBC
5. • JDBC is a Java-based data access technology (Java
Standard Edition platform) from Oracle Corporation.
• Sun Microsystems released JDBC as part of JDK 1.1 on
February 19, 1997.[1] It has since formed part of the
Java Standard Edition.
• The JDBC classes are contained in the Java
package java.sql and javax.sql.
• Starting with version 3.1, JDBC has been developed under
the Java Community Process. JSR 54 specifies JDBC 3.0
(included in J2SE 1.4), JSR 114 specifies the JDBC Rowset
additions, and JSR 221 is the specification of JDBC 4.0
(included in Java SE 6).[2]
• The latest version, JDBC 4.1, is specified by a maintenance
release of JSR 221[3] and is included in Java SE 7.[4]
June 21, 2017 5
JDBC History
6. • JDBC 2.0
– Support for data types, such as objects, arrays, and large objects
(LOBs). This is handled through the standard java.sql package.
– Support for standard features, such as result set enhancements and
update batching. This is handled through standard objects, such
as Connection,ResultSet, and PreparedStatement, under JDK 1.2.x
and later.
– Support for extended features, such as features of the JDBC 2.0
optional package, also known as the standard extension application
programming interface (API), including data sources, connection
pooling, and distributed transactions
June 21, 2017 6
JDBC Example
7. • JDBC 2.0
– Transaction Savepoints
– Retrieval of Auto-Generated Keys
– JDBC 3.0 LOB Interface Methods
– Result Set Holdability
• JDBC 4.0
– Wrapper Pattern Support
– Enhanced Exception Hierarchy and SQLException
– The RowId Data Type
– LOB Creation
– National Language Character Set Support
• JDBC 4.1
– The ability to use a try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement
– RowSet 1.1: The introduction of the RowSetFactory interface and the
RowSetProvider class, which enable you to create all types of row sets
supported by your JDBC driver.
June 21, 2017 7
JDBC Example
8. • Classes
– locate DBMS drivers - DriverManagerClass
• locates the driver for DB you specify
– establish connections
• commit, rollback and the DB isolation level
– submit SQL statements
• 2 extensions
– Prepared statement - precompile and execute
– Callable statement - stored procedures
– process result set
• manipulate the cursor and get back results
June 21, 2017 8
JDBC Core
9. June 21, 2017 9
JDBC Drivers
- JDBC drivers implement the defined interfaces in the JDBC
API for interacting with your database server
- Using JDBC drivers enable you to open database
Connections and to interact with it by sending SQL or database
commands then receiving results with Java
10. June 21, 2017 10
Type 1 JDBC Drivers
• Type 1 : This driver converts JDBC calls to ODBC calls
through JDBC-ODBC Bridge driver which in turn converts to
database calls. Client requires ODBC libraries.
• a JDBC bridge is used to access ODBC drivers installed on
each client machine. Using ODBC requires configuring on
your system a Data Source Name (DSN) that represents the
target database.
11. June 21, 2017 11
Type 2 JDBC Drivers
• Type 2 : This driver converts JDBC calls to database
specific native calls. Client requires database specific
libraries.
• 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
• E.g:- Oracle call Interface(OCI)
12. June 21, 2017 12
Type 3 JDBC Drivers
• Type 3 : This driver passes calls to proxy server through
network protocol which in turn converts to database calls and
passes through database specific protocol. Client doesn't
require any driver.
• 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.
13. June 21, 2017 13
Type 4 JDBC Drivers
• Type 4 This driver directly calls database. Client doesn't
require any driver.
• 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.
14. June 21, 2017 14
Benchmarking JDBC Drivers
• Type 4 - Accessing one type of database, such as Oracle,
Sybase, or MySQL.
• Type 3 - Accessing Multiple types of database at the same
time
• Type 2 - In case 3 or 4 not available on your machine
• Type 1 - Drivers are not considered for deployment, only for
development and testing
15. • Import the JDBC Package
• Set useful static class variables for driver, DBMS URI,
credentials, etc.
• Register appropriate driver with the DriverManager class
• Set connection Properties (typically credentials)
• Invoke the Connection
• Create SQL statement in a String
• Invoke Statement on connection
• Execute SQL statement via appropriate method on
Statement object.
Continued…
June 21, 2017 15
Typical Steps
16. • execute(...), executeQuery(...) for SELECT to receive
ResultSet/s.
• executeUpdate(...) for INS/DEL/UPD or DDLs, receive
integer value indicating row count .
• automatic commit, unless disabled, in which case an explicit
COMMIT must be executed to save changes to database.
• Check for Exceptions.
• Process ResultSet
• Close ResultSet and Statement
• Unless multiple transactions, then redefine and reuse
• Cycle for further operations
• Close Connection
June 21, 2017 16
Typical Steps
17. • oracle.jdbc.driver (classes to support database access and
updates in Oracle type formats)
• Load the Oracle JDBC driver
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
or
Class.forName ("oracle.jdbc.driver.OracleDriver");
• Connect to the database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@learning", “root", “pwd");
June 21, 2017 17
Registering & Connecting:The DriverManager Class
18. • Code for creating a connection using JDBC with Oracle
try
{ // register the driver to connect to oracle
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
// db_con is a connection object that lets us connect to the
// database with specified URL/userid/password
Connection db_con = DriverManager.getConnection
("jdbc:oracle:thin:@llama.its.monash.edu.au:1521:CSE
5200A", "studentid", "password");
System.out.println("Connection Success");
} catch(SQLException f ){
// gives error if the above did not succeed.
System.out.println("Connection Failed. SQL Exception");
• }
June 21, 2017 18
Sample Code
19. • Code to retrieve data from the Database using the previously
created JDBC Connection object.
try
{ // statement object stmt created to execute queries using
//db_con
Statement stmt = db_con.createStatement();
// resultset is an object that holds the result of the query
ResultSet rset = stmt.executeQuery ("SELECT * FROM
authors");
// looping through the resultset object till end
while (rset.next()){
// getString gets the string data in col 1 of result
// and we would have rset.getInt(2) if col 2 was an integer
System.out.println (rset.getString(1));
}June 21, 2017 19
Sample Code
20. } catch(SQLException f) {
// error handling for above
System.out.println("Cannot retrieve data SQL Exception
occured");
}
June 21, 2017 20
Sample Code
21. • Connection Interface
– Session between application and database
– Specified by location (URI) and credentials
• Commit/Rollback
– conn.commit();
– conn.rollback();
• Set Autocommit off
– after connect but before any statement
• conn.setAutoCommit (false);
June 21, 2017 21
Transactions:The Connection Interface
22. • Statement stmt = conn.createStatement ();
• stmt.execute (“select empno from emp”);
– no parameters
• PreparedStatement pmst = conn.prepareStatement
(“insert into emp (EMPNO, EMPNAME) values (?, ?)”);
- setting and getting parameters in next slides.
• pstmt.execute();
• selectText = "SELECT firstname,lastname FROM
addresses";
Continued…
June 21, 2017 22
Creating a Statement Object:Connection Interface
23. • Statement selectStmt = dbConnection.createStatement();
• ResultSet result = selectStmt.executeQuery(selectText);
• insertText = "INSERT INTO addresses VALUES
(1,'John','Smith')";
• Statement insertStmt = dbConnection.createStatement();
• int rowsInserted = insertStmt.executeUpdate(insertText);
June 21, 2017 23
Creating a Statement Object:Connection Interface
24. • PreparedStatement
• statement is pre-compiled and stored in a
PreparedStatement object. Can use this to efficiently
execute the statement multiple times
• allows IN parameters within the query
• referenced by number
• setXXX () methods used
• setXXX();
– pstmt.setString (1, "SCOTT");
• getXXX();
– System.out.println( rset.getString (1) );
• setNULL(); - don’t use nulls
June 21, 2017 24
Setting Parameters & Getting Fields
25. • Provides access to a table of data generated by executing a
Statement
• Table rows are retrieved in sequence via a cursor pointing
to the current row of data
• Some methods:
• next ()
• getXXX () methods
• wasNull ()—detect SQL NULL values
• close ()
June 21, 2017 25
ResultSet Interface
26. • ResultSet rset = stmt.executeQuery ("SELECT ename
FROM emp");
• executeUpdate
– insert, delete, update
• execute():
• while (rset.next())
System.out.println (rset.getString(1));
• This is standard JDBC syntax. The next() method returns
false when it reaches the end of the result set. The
employee names are materialized as JavaStrings.
June 21, 2017 26
Executing a Query and Returning the ResultSet Interface
27. • You must explicitly close the ResultSet and Statement
objects after you finish using them.
• rset.close();
• stmt.close();
• You must close your connection to the database once you
finish your work.
• conn.close();
June 21, 2017 27
Closing the ResultSet, Statement and Connection
29. • getMessage(): returns the error message associated with
the object that threw the exception
• printStackTrace(): prints this object name and its stacktrace
to the specified print stream
• This example uses both getMessage() and
printStackTrace() to return errors.
catch(SQLException e); {
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
OR
Continued…
June 21, 2017 29
SQLException