JDBC provides an API for accessing databases from Java that simplifies development, supports metadata access, and allows connection pooling. It includes interfaces for application writers and driver writers, with popular drivers available for databases like Oracle, MySQL, and SQL Server. JDBC drivers can be Type 1 (JDBC-ODBC bridge), Type 2 (partial JDBC), Type 3 (pure Java for middleware), or Type 4 (direct connection).
2. 2
What is JDBC?
“An API that lets you access virtually any tabular
data source from the Java programming
language”
JDBC Data Access API – JDBC Technology
Homepage
tabular data source?
“… access virtually any data source, from
relational databases to spreadsheets and flat
files.”
JDBC Documentation
We’ll focus on accessing Oracle databases
3. Advantages
1. Simplified Enterprise Development:
By integrating with java JDBC code becomes very less. It is
simple to install and maintain. Easy to write JDBC program
2. Zero Configuration for Network computers:
No configuration is required. We require a suitable driver to
connect to the database. It may be a bridge driver or a driver
written in java.
3. Full Access to Metadata: JDBC API includes classes
and interfaces to obtain metadata.
4. No Installation:
4. 5. Database connection identified by URL: connectivity
through DataSource object. Data source objects can provide
connection pooling and transaction management.
6. Included in the J2EE platform: As JDBC API is needed in
enterprise applications to connect to databases, it is included in
the java2.0 Enterprise Edition.
Advantages
5. JDBC API
It contains two main interfaces.
1. An API for application writers and
2. A lower level driver API for driver writers.
The set of classes that implement these lower level API
interfaces for a particular database engine is called a
JDBC driver
A program needs a specific driver to connect to a specific
database
6. Popular Drivers
Driver RDBMS
Oracle.jdbc.driver.OracleDriver ORACLE
Com.mysql.jdbc.Driver MySQL
Com.sybase.jdbc.SybDriver Sybase
Com.microsoft.jdbc.sqlserver.SQLServer
Driver
SQL Server
Com.ibm.db2.jdbc.net.DB2Driver DB2
Org.hsqldbJdbcDriver HSQL DB
7. Types of Drivers
1. Type1 ( JDBC-ODBC bridge + ODBC driver)
2. Type2 (partial JDBC driver)
3. Type3 (pure java JDBC driver for database
middleware)
4. Type4 (pure Java JDBC driver with a direct
database connection)
8. Type 1 driver
Allows an application to access database through an
intermediate ODBC driver.
It provides a gateway to the ODBC API
Disadvantages:
1. ODBC binary code must be loaded on each client
machine that uses this driver, limiting the usefulness of
this type of driver for the internet
2. Translation overhead between JDBC and ODBC
3. User is limited by the functionality of the underlying ODBC
driver.
4. Doesn’t support all the features of java.
5. It only works under the Microsoft windows and Sun
Solaris operating systems.
9. Type 2, 3,4 Drivers
Type 2-driver converts JDBC calls into client API calls for
the DBMS. Also communicates directly with the database
server. This driver offers better performance than type 1
driver.
Type-3 driver is completely implemented in java, hence it
is a pure java JDBC driver. It translates JDBC calls into
the middleware vendors’ protocol and translated to a
DBMS protocol by a middleware server.
Type-4 drivers talks directly to the database using java
sockets. These type of drivers are completely
implemented in java to achieve platform independence
and eliminate deployment issues. This type of drivers
comes from the database vendor.
10. 10
General Architecture
What design pattern is
implied in this
architecture?
What does it buy for us?
Why is this architecture
also multi-tiered?
12. 12
Basic steps to use
a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
13. 13
1. Establish a connection
import java.sql.*;
Load the vendor specific driver
Class.forName("oracle.jdbc.driver.OracleDriver");
What do you think this statement does, and how?
Dynamically loads a driver class, for Oracle database
Make the connection
Connection con =
DriverManager.getConnection( "jdbc:oracle:thin:@oracl
e-prod:1521:OPROD", username, passwd);
What do you think this statement does?
Establishes connection to database by obtaining
a Connection object
14. 14
2. Create JDBC statement(s)
Statement stmt = con.createStatement() ;
Creates a Statement object for sending SQL statements
to the database
15. 15
Executing SQL Statements
String createLehigh = "Create table Lehigh " +
"(SSN Integer not null, Name VARCHAR(32), " +
"Marks Integer)";
stmt.executeUpdate(createLehigh);
//What does this statement do?
String insertLehigh = "Insert into Lehigh values“
+ "(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);
16. 16
Get ResultSet
String queryLehigh = "select * from Lehigh";
ResultSet rs = Stmt.executeQuery(queryLehigh);
//What does this statement do?
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
18. 18
Transactions and JDBC
JDBC allows SQL statements to be grouped together into a
single transaction
Transaction control is performed by the Connection object,
default mode is auto-commit, I.e., each sql statement is treated
as a transaction
We can turn off the auto-commit mode with
con.setAutoCommit(false);
And turn it back on with con.setAutoCommit(true);
Once auto-commit is off, no SQL statement will be committed
until an explicit is invoked con.commit();
At this point all changes done by the SQL statements will be
made permanent in the database.
19. 19
Handling Errors with
Exceptions
Programs should recover and leave the database in
a consistent state.
If a statement in the try block throws an exception or
warning, it can be caught in one of the
corresponding catch statements
How might a finally {…} block be helpful here?
E.g., you could rollback your transaction in a
catch { …} block or close database connection and
free database related resources in finally {…} block
20. 20
Another way to access database
(JDBC-ODBC)
What’s a bit different
about this
architecture?
Why add yet
another layer?
21. 21
Sample program
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver
String filename = "c:/db1.mdb"; //Location of an Access database
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; //add on to end
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute("create table TEST12345 ( firstcolumn integer )");
s.execute("insert into TEST12345 values(1)");
s.execute("select firstcolumn from TEST12345");
22. 22
Sample program(cont)
ResultSet rs = s.getResultSet();
if (rs != null) // if rs == null, then there is no ResultSet to view
while ( rs.next() ) // this will step through our data row-by-row
{ /* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("Data from column_name: " + rs.getString(1) );
}
s.close(); // close Statement to let the database know we're done with it
con.close(); //close connection
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}
}
24. 24
JDBC 2 – Scrollable Result Set
…
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
String query = “select students from class where type=‘not sleeping’ “;
ResultSet rs = stmt.executeQuery( query );
rs.previous(); / / go back in the RS (not possible in JDBC 1…)
rs.relative(-5); / / go 5 records back
rs.relative(7); / / go 7 records forward
rs.absolute(100); / / go to 100th record
…
25. 25
JDBC 2 – Updateable ResultSet
…
Statement stmt =
con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
String query = " select students, grade from class
where type=‘really listening this presentation’ “;
ResultSet rs = stmt.executeQuery( query );
…
while ( rs.next() )
{
int grade = rs.getInt(“grade”);
rs.updateInt(“grade”, grade+10);
rs.updateRow();
}
26. 26
Metadata from DB
A Connection's database is able
to provide schema information
describing its tables,
its supported SQL grammar,
its stored procedures
the capabilities of this connection, and so on
What is a stored procedure?
Group of SQL statements that form a logical unit
and perform a particular task
This information is made available through
a DatabaseMetaData object.
28. 28
JDBC – Metadata from RS
public static void printRS(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
// get number of columns
int nCols = md.getColumnCount();
// print column names
for(int i=1; i < nCols; ++i)
System.out.print( md.getColumnName( i)+",");
/ / output resultset
while ( rs.next() )
{ for(int i=1; i < nCols; ++i)
System.out.print( rs.getString( i)+",");
System.out.println( rs.getString(nCols) );
}
}
29. 29
JDBC and beyond
(JNDI) Java Naming and Directory Interface
API for network-wide sharing of information about users,
machines, networks, services, and applications
Preserves Java’s object model
(JDO) Java Data Object
Models persistence of objects, using RDBMS as repository
Save, load objects from RDBMS
(SQLJ) Embedded SQL in Java
Standardized and optimized by Sybase, Oracle and IBM
Java extended with directives: # sql
SQL routines can invoke Java methods
Maps SQL types to Java classes
30. JDBC API
PreparedStatement
• Represents a precompiled SQL statement
• Can be used to efficiently execute
statement multiple times
• Somewhat flexible – can create new ones
as needed
A prepared statement can contain variables that
you supply each time you execute the statement.
31. Optimized Statements
Prepared Statements
SQL calls that you make again and again
allows driver to optimize (compile) queries
created with Connection.prepareStatement()
Stored Procedures
written in DB-specific language
stored inside database
accessed with Connection.prepareCall()
32. Prepared Statements Performance
Prepared Statements are more
efficient than Statements when
executing SQL statements multiple times
and with different parameter values.
34. PreparedStatements
PreparedStatement to locate all book titles for
an author with a specific last name and first name,
and to execute that query for several authors:
PreparedStatement authorBooks =
connection.prepareStatement(
"SELECT lastName, firstName, title " +
"FROM authors INNER JOIN authorISBN " +
"ON authors.authorID=authorISBN.authorID "
+
"INNER JOIN titles " +
"ON authorISBN.isbn=titles.isbn " +
"WHERE lastName = ? AND firstName = ?" );
Question marks (?) are placeholders for values that
will be passed as part of the query to the database
35. PreparedStatements
Program must specify the parameter values by
using the PreparedStatement interface’s set
methods.
For the preceding query, both parameters are
strings that can be set with PreparedStatement
method setString as follows:
authorBooks.setString( 1, "Deitel" );
authorBooks.setString( 2, "Paul" );
setString automatically escapes String
parameter values as necessary (e.g., the quote in
the name O’Brien)
36. Prepared Statement Example
PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast",
"Espresso","Colombian_Decaf","French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
}
38. The Callable Statement Object
A Callable Statement 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
Callable Statement object.
40. CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM + "(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);
How to Create a Callable
Statement
Register the driver and create the database
connection.
Create the callable statement, identifying
variables with a question mark (?).
41. How to Execute
a callable
Statement
How to Execute
a callable
Statement
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
43. Three-Tier Architecture
Oracle
DB Server
Apache Tomcat
App Server
Microsoft
Internet
Explorer
HTML
Tuples
HTTP
Requests
JDBC
Requests
Java Server
Pages (JSPs)
Located
@ DBLab
Located
@ Your PC
Located
@ Any PC
44. import java.sql.*;
class JdbcTest {
public static void main (String args []) throws SQLException {
// Load Oracle driver
DriverManager.registerDriver (new
oracle.jdbc.driver.OracleDriver());
// Connect to the local database
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myhost:1521:ORCL","scott", "tiger");
JDBC
45. // Query the student names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT name FROM Student");
// Print the name out
//name is the 2nd
attribute of Student
while (rset.next ())
System.out.println (rset.getString (2));
//close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
47. Entry Form - First Attempt
<b>Data Entry Menu</b>
<ul>
<li>
<a href="courses.jsp">Courses<a>
</li>
<li>
<a href="classes.jsp">Classes<a>
</li>
<li>
<a href="students.jsp">Students<a>
</li>
</ul>
Menu HTML Code
48. Entry Form - First Attempt
<html>
<body>
<table>
<tr>
<td>
<jsp:include page="menu.html" />
</td>
<td>
Open connection code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
49. Entry Form - First Attempt
<%-- Set the scripting language to java and --%>
<%-- import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
// Make a connection to the Oracle datasource
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@feast.ucsd.edu:1521:source",
“user", “pass");
%>
Open Connectivity Code
50. Entry Form - First Attempt
<%
// Create the statement
Statement statement = conn.createStatement();
// Use the statement to SELECT the student attributes
// FROM the Student table.
ResultSet rs = statement.executeQuery
("SELECT * FROM Student");
%>
Statement Code
51. Entry Form - First Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
53. Entry Form - First Attempt
<tr>
<%-- Get the SSN, which is a number --%>
<td><%= rs.getInt("SSN") %></td>
<%-- Get the ID --%>
<td><%= rs.getString("ID") %></td>
<%-- Get the FIRSTNAME --%>
<td><%= rs.getString("FIRSTNAME") %></td>
<%-- Get the LASTNAME --%>
<td><%= rs.getString("LASTNAME") %></td>
<%-- Get the COLLEGE --%>
<td><%= rs.getString("COLLEGE") %></td>
</tr>
Iteration Code
54. Entry Form - First Attempt
<%
// Close the ResultSet
rs.close();
// Close the Statement
statement.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
%>
Close Connectivity Code
56. Entry Form - Second Attempt
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
57. Entry Form - Second Attempt
// Check if an insertion is requested
String action = request.getParameter("action");
if (action != null && action.equals("insert")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// INSERT the student attrs INTO the Student table.
PreparedStatement pstmt = conn.prepareStatement(
("INSERT INTO Student VALUES (?, ?, ?, ?, ?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN")));
pstmt.setString(2, request.getParameter("ID"));
…
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Insertion Code
58. Entry Form - Second Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
61. Entry Form - Third Attempt
<html>
<body>
<table>
<tr>
<td>
Open connection code
Insertion Code
Update Code
Delete Code
Statement code
Presentation code
Close connection code
</td>
</tr>
</table>
</body>
</html>
JSP Code
62. Entry Form - Third Attempt
// Check if an update is requested
if (action != null && action.equals("update")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// UPDATE the student attributes in the Student table.
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE Student SET ID = ?, FIRSTNAME = ?, " +
"LASTNAME = ?, COLLEGE = ? WHERE SSN = ?");
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
…
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Update Code
63. Entry Form - Third Attempt
// Check if a delete is requested
if (action != null && action.equals("delete")) {
conn.setAutoCommit(false);
// Create the prepared statement and use it to
// DELETE the student FROM the Student table.
PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Student WHERE SSN = ?");
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));
int rowCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Delete Code
64. Entry Form - Third Attempt
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table>
Presentation Code
The CallableStatement Object
The way to access stored procedures using JDBC is through the CallableStatement class which is inherited from the PreparedStatement class. CallableStatement is like PreparedStatement in that you can specify parameters using the question mark (?) notation, but it contains no SQL statements.
Both functions and procedures take parameters represented by identifiers. A function executes some procedural logic and it returns a value that can be any data type supported by the database. The parameters supplied to the function do not change after the function is executed.
A procedure executes some procedural logic but does not return any value. However, some of the parameters supplied to the procedure may have their values changed after the procedure is executed.
Note: Calling a stored procedure is the same whether the stored procedure was written originally in Java or in any other language supported by the database, such as PL/SQL. Indeed, a stored procedure written in Java appears to the programmer as a PL/SQL stored procedure.
Creating a Callable Statement
First you need an active connection to the database in order to obtain a CallableStatement object.
Next, you create a CallableStatement object using the prepareCall() method of the Connection class. This method typically takes a string as an argument. The syntax for the string has two forms. The first form includes a result parameter and the second form does not:
{? = call proc (…) } // A result is returned into a variable{call proc (…) } // Does not return a result
In the example in the slide, the second form is used, where the stored procedure in question is ADDITEM.
Note that the parameters to the stored procedures are specified using the question mark notation used earlier in PreparedStatement. You must register the data type of the parameters using the registerOutParameter() method of CallableStatement if you expect a return value, or if the procedure is going to modify a variable (also known as an OUT variable). In the example in the slide, the second and third parameters are going to be computed by the stored procedure, whereas the first parameter is an input (the input is specified in the next slide). Parameters are referred to sequentially, by number. The first parameter is 1.
To specify the data type of each OUT variable, you use parameter types from the Types class. When the stored procedure successfully returns, the values can be retrieved from the CallableStatement object.
How to Execute a Callable Statement
There are three steps in executing the stored procedure after you have registered the types of the OUT variables:
1.Set the IN parameters.
Use the setXXX() methods to supply values for the IN parameters. There is one setXXX() method for each Java type: setString(), setInt(), and so on. You must use the setXXX() method that is compatible with the SQL type of the variable. You can use setObject() with any variable type. Each variable has an index. The index of the first variable in the prepared statement is 1, the index of the second is 2, and so on. If there is only one variable, its index is 1.
2.Execute the call to the stored procedure.
Execute the procedure using the execute() method.
3.Get the OUT parameters.
Once the procedure is completed, you retrieve OUT variables, if any, using the getXXX() methods. Note that these methods must match the types you registered in the previous slide.
Instructor Note
The stored procedures lesson contains an example of executing a callable statement.