JDBC –Java DataBase Connectivity
Sasidhar
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
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:
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
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
Popular Drivers
Driver RDBMS
Oracle.jdbc.driver.OracleDriver ORACLE
Com.mysql.jdbc.Driver MySQL
Com.sybase.jdbc.SybDriver Sybase
Com.microsoft.jdbc.sqlserver.SQLServerDriver
SQL Server
Com.ibm.db2.jdbc.net.DB2Driver DB2
Org.hsqldbJdbcDriver HSQL DB
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)
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.
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
General Architecture
What design pattern is implied in this architecture?
What does it buy for us? Why is this architecture
also multi-tiered?
11
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
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:@oracle-prod:1521:OPROD", username, passwd);
What do you think this statement does? Establishes connection to database by obtaining
a Connection object
14
2. Create JDBC statement(s)
Statement stmt = con.createStatement() ; Creates a Statement object for sending SQL statements
to the database
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
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");
}
17
Close connection
stmt.close(); con.close();
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
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
Another way to access database(JDBC-ODBC)
What’s a bit differentabout this architecture?
Why add yet another layer?
21
Sample programimport 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
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); } }}
23
Mapping types JDBC - Java
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 backrs.relative(7); / / go 7 records forwardrs.absolute(100); / / go to 100th record…
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
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.
27
Metadata from DB - example…Connection con = …. ;
DatabaseMetaData dbmd = con.getMetaData();
String catalog = null; String schema = null;String table = “sys%”; String[ ] types = null;
ResultSet rs =dbmd.getTables(catalog , schema , table , types );
…
28
JDBC – Metadata from RS
public static void printRS(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData(); // get number of columnsint nCols = md.getColumnCount();// print column namesfor(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
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
JDBC API
PreparedStatement• Represents a precompiled SQL statement• Can be used to efficiently execute
statement multiple times• Somewhat flexible – can create new ones
as neededA prepared statement can contain variables that
you supply each time you execute the statement.
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()
Prepared Statements Performance
Prepared Statements are more efficient than Statements when executing SQL statements multiple times and with different parameter values.
Prepared Statements
PreparedStatements execute more efficiently than Statement objects
PreparedStatements can specify parameters
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
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)
Prepared Statement ExamplePreparedStatement 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();
}
JDBC Class Diagram
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.
JDBC API
java.sql.CallableStatement• Used to execute SQL stored procedures. • Same syntax as PreparedStatement.• Least flexible.• Most optimized DB call.
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 (?).
How to Execute a callable Statement
How to Execute a callable Statement
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
Database access through JSP
Three-Tier Architecture
OracleDB Server
Apache TomcatApp Server
MicrosoftInternetExplorer
HTML
Tuples
HTTPRequests
JDBCRequests
Java ServerPages (JSPs)
Located@ DBLab
Located@ Your PC
Located@ Any PC
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
// 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 Studentwhile (rset.next ())
System.out.println (rset.getString (2));
//close the result set, statement, and the connection rset.close();stmt.close(); conn.close();
JSP SyntaxComment
<%-- Comment --%>
Expression <%= java expression %>
Scriplet <% java code fragment %>
Include <jsp:include page="relativeURL" />
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
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
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
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
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
Entry Form - First Attempt
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
Entry Form - First Attempt
<%// Close the ResultSetrs.close(); // Close the Statementstatement.close(); // Close the Connectionconn.close();
} catch (SQLException sqle) { out.println(sqle.getMessage());} catch (Exception e) { out.println(e.getMessage());}%>
Close Connectivity Code
Entry Form - Second Attempt
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
Entry Form - Second Attempt
// Check if an insertion is requestedString 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
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
Entry Form - Second Attempt
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>
Insert Form Code
Entry Form - Third Attempt
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
Entry Form - Third Attempt
// Check if an update is requestedif (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
Entry Form - Third Attempt
// Check if a delete is requestedif (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
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
Entry Form - Third Attempt
<tr> <form action="students.jsp" method="get"> <input type="hidden" value="update" name="action"> <td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td> <td><input value="<%= rs.getString("ID") %>" name="ID"></td>… <td><input type="submit" value="Update"></td> </form> <form action="students2.jsp" method="get"> <input type="hidden" value="delete" name="action"> <input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN"> <td><input type="submit" value="Delete"></td> </form></tr>
Iteration Code