Using JDBC to Access the Database

Copyright © 2009, Oracle. All rights reserved.

After completing this lesson, you should be able to do the following: • Describe how Java code connects to the database • Describe how Java database functionality is supported by the Oracle database • Load and register a JDBC driver • Connect to an Oracle database • Perform a simple SELECT statement • • Map simple Oracle database types to Java types Use a pooled connection

15 - 2

Copyright © 2009, Oracle. All rights reserved.

Java, Java EE, and Oracle 11g
Web server


Application server
Business logic


Oracle Application Server 11g Java EE Certified Environment

Oracle database


15 - 3

Copyright © 2009, Oracle. All rights reserved.

and servlets use JDBC. JSPs.Connecting to a Database with Java Client applications.4 Copyright © 2009. . Client application or applet JDBC Relational database 15 . Oracle. All rights reserved.

sql. The JDBC class library is part of Java Platform. Copyright © 2009. Oracle. – JDBC 3. – The JDBC API includes the Core API Package in java. Standard Edition (Java SE).0 API includes the Core API and Optional Package API. . – JDBC 2.0 API includes the Optional Package API in javax. • • 15 . All rights reserved.sql.Java Database Connectivity (JDBC) • JDBC is a standard API for connecting to relational databases from Java.5 You must include the Oracle JDBC driver archive file in the CLASSPATH.

sql. import java. • Include the JDBC driver classes in the classpath settings. // optional // Oracle extension to JDBC packages import oracle. All rights reserved.math.*. Oracle.6 Copyright © 2009.Preparing the Environment • Import the JDBC packages: // Standard packages import java. .*. 15 .*.sql. import oracle.jdbc.*.

2. 15 . or DDL statement. 4. Create statement object.7 Copyright © 2009. Obtain a connection. . Execute SQL statement. Clean up. Oracle. Code the 4b. Process DML Query Statement.Steps for Using JDBC to Execute SQL Statements 1. 6. Register JDBC driver. 3. 4a. 5. Process query results. All rights reserved.

OracleDriver").Step 1: Register the Driver • Register the driver in the code: – DriverManager. – Class. • Register the driver when launching the class: – java -Djdbc. All rights reserved.drivers=oracle.registerDriver (new oracle.jdbc.jdbc.OracleDriver()). .OracleDriver <ClassName>. 15 .forName ("oracle.8 Copyright © 2009. Oracle.jdbc.

Connecting to the Database Using the package oracle. . Oracle. All rights reserved.jdbc. Oracle provides different drivers to establish a connection to the database. OracleDriver JDBC calls • Thin client • OCI-based • Server-based •… Database commands Database 15 .9 Copyright © 2009.driver.

. All rights reserved.Oracle JDBC Drivers: Thin-Client Driver • • Is written entirely in Java Must be used by applets Applet JDBC Thin driver Client Oracle Server 15 .10 Copyright © 2009. Oracle.

Oracle.Oracle JDBC Drivers: OCI Client Driver • • Is written in C and Java Must be installed on the client Application JDBC OCI driver ocixxx.dll Client Oracle Server 15 .11 Copyright © 2009. . All rights reserved.

12 Copyright © 2009. .Choosing the Right Driver Type of Program Applet Client application EJB. Oracle. All rights reserved. servlet (on the middle tier) Driver Thin Thin Thin OCI Server side OCI Stored procedure 15 .

which provides overloaded getConnection()methods. Oracle. . use the DriverManager class. "scott". • Example: Connection conn = DriverManager.Step 2: Obtain a Database Connection • In JDBC 1.0. All rights reserved."tiger"). – All connection methods require a JDBC URL to specify the connection details. 15 .getConnection( "jdbc:oracle:thin:@myhost:1521:ORCL".13 Copyright © 2009. • Vendors can provide different types of JDBC drivers.

.14 Copyright © 2009. which vary depending on the driver used jdbc:<subprotocol>:<subname> Protocol Database identification jdbc:oracle:<driver>:@<database> • Example using the Oracle JDBC Thin driver: – jdbc:oracle:thin:@myhost:1521:ORCL 15 . Oracle.JDBC URLs • JDBC uses a URL-like string. All rights reserved. the URL identifies: – The JDBC driver to use for the connection – Database connection details.

Oracle.JDBC URLs with Oracle Drivers • Oracle JDBC Thin driver Syntax: jdbc:oracle:thin:@<host>:<port>:<SID> Example: "jdbc:oracle:thin:@eduhost:1521:orcl" • Oracle JDBC OCI driver Syntax: jdbc:oracle:oci:@<tnsname entry> Example: "jdbc:oracle:oci:@orcl" 15 . .15 Copyright © 2009. All rights reserved.

15 . which provides a context for executing a SQL statement. • Use the createStatement()method.getConnection( "jdbc:oracle:thin:@myhost:1521:ORCL".createStatement(). "scott". Oracle."tiger"). • Example: Connection conn = DriverManager. Statement stmt = conn.Step 3: Create a Statement JDBC statement objects are created from the Connection instance.16 Copyright © 2009. . All rights reserved.

– Returns an int execute(String) for any SQL statement – Returns a boolean value 15 .17 Copyright © 2009. All rights reserved. . Oracle.Using the Statement Interface The Statement interface provides three methods to execute SQL statements: • executeQuery(String sql)for SELECT statements – Returns a ResultSet object for processing rows • • executeUpdate(String sql) for DML or DDL.

Step 4a: Code the Query Statement Provide a SQL query string. All rights reserved. • Returns a ResultSet object: Statement stmt = null. rset = stmt. . ResultSet rset = null. as an argument to the executeQuery()method.executeQuery ("SELECT ename FROM emp"). without semicolon. 15 .createStatement(). stmt = conn.18 Copyright © 2009. Oracle.

ResultSet Object • • The JDBC driver returns the results of a query in a ResultSet object. Oracle. ResultSet: – Maintains a cursor pointing to its current row of data – Provides methods to retrieve column values 15 .19 Copyright © 2009. . All rights reserved.

15 .20 Copyright © 2009. Example: Statement stmt = conn.executeUpdate ("DELETE FROM order_items WHERE order_id = 2354").createStatement().createStatement().Step 4b: Submit DML Statements 1. Create an empty statement object. int rowcount = stmt.executeUpdate(SQLDMLstatement). Use executeUpdate to execute the statement. int count = stmt. . 2. All rights reserved. Oracle. Statement stmt = conn.

15 .Step 4b: Submit DDL Statements 1. All rights reserved.executeUpdate(SQLDDLstatement). int rowcount = stmt. . 2.createStatement(). Statement stmt = conn.2). int count = stmt.executeUpdate ("CREATE TABLE temp (col1 NUMBER(5. Use executeUpdate to execute the statement. Example: Statement stmt = conn.21 Copyright © 2009.createStatement(). Create an empty statement object. Oracle. col2 VARCHAR2(30)").

next()) { System.executeQuery( "SELECT ename FROM emp"). Oracle. All rights reserved. • Use the next()method in loop to iterate through rows.22 Copyright © 2009. while (rset. • Use getXXX()methods to obtain column values by column name or by column position in query. } 15 .out.Step 5: Process the Query Results The executeQuery()method returns a ResultSet. .createStatement(). stmt = conn.getString("ename")).println (rset. rset = stmt.

Date hiredate ={ int id = rset. while (rset. Column Name empno hiredate job NUMBER DATE VARCHAR2 Type Method getInt() getDate() getString() 15 . Oracle. . All rights reserved.getString(3).23 Copyright © 2009. hiredate.Mapping Database Types to Java Types ResultSet maps database types to Java types: ResultSet rset = stmt.getInt(1). String job = rset. job FROM emp").getDate(2).executeQuery ("SELECT empno.

Oracle. .25 Copyright © 2009.. ResultSet rset = stmt..close(). Statement.Step 6: Clean Up Explicitly close a Connection. .... stmt...close(). Statement stmt = .. conn. and ResultSet object to release resources that are no longer needed.close(). // clean up rset.. All rights reserved. • Call their respective close()methods: Connection conn = .executeQuery( "SELECT ename FROM emp").. . 15 .

26 Copyright © 2009. Connection conn = DriverManager.*.close()."scott".getString ("ename")).getConnection ("jdbc:oracle:thin:@myHost:1521:ORCL".out. import oracle. All rights reserved.Basic Query Example import java. stmt.jdbc.driver. ResultSet rset = stmt.sql.close().println (rset. class TestJdbc { public static void main (String args [ ]) throws SQLException { DriverManager.close().OracleDriver.createStatement().executeQuery ("SELECT ename FROM emp"). while (rset.registerDriver (new oracle. Oracle. } } 15 . "tiger"). .next()) System.OracleDriver()). Statement stmt = conn.jdbc. conn. rset.

..getResultSet(). 3.createStatement(). . Process the statement accordingly. 2. Statement stmt = conn. boolean isQuery = stmt.process result int count = stmt.process results ResultSet r = stmt.27 Copyright © 2009. .Handling an Unknown SQL Statement 1. } 15 .getUpdateCount(). Create an empty statement object. Oracle..execute(SQLstatement). if (isQuery) { // was a query . Use execute to execute the statement. . } else { // was an update or DDL .. All rights reserved.

sql.Handling Exceptions • • SQL statements can throw a java. ename FROM emp").... finally { // clean up try { if (rset != null) rset. Oracle. 15 ..SQLException..executeQuery("SELECT empno.sql.28 Copyright © 2009. . } catch (java... } catch (Exception e) { . Use standard Java error handling methods. /* handle SQL errors */ } . try { rset = stmt. All rights reserved.SQLException e) { . /* handle closing errors */ } .close()..

.rollback()to roll back a transaction • Closing a connection commits the transaction even with autocommit disabled. Use conn. 15 .setAutoCommit(false)to disable autocommit.Transactions with JDBC • • • By default. use: – conn.29 Copyright © 2009. connections are in autocommit mode.commit()to commit a transaction – conn. All rights reserved. Oracle. To control transactions when you are not in autocommit mode.

15 .31 Copyright © 2009.PreparedStatement Object • • • A prepared statement prevents reparsing of SQL statements. All rights reserved. Oracle. . Use the PreparedStatement object for statements that you want to execute more than once. A prepared statement can contain variables that you supply each time you execute the statement.

Creating a PreparedStatement Object 1. PreparedStatement pstmt = conn. 2. Create the PreparedStatement object. identifying variables with a question mark (?). 15 .prepareStatement ("SELECT ename FROM emp WHERE empno = ?"). PreparedStatement pstmt = conn. Register the driver and create the database connection. Oracle. . All rights reserved.32 Copyright © 2009.prepareStatement ("UPDATE emp SET ename = ? WHERE empno = ?").

Oracle. All rights reserved. int empNo = 3521. "DURAND").Executing a PreparedStatement Object 1. pstmt. pstmt. 15 .prepareStatement("UPDATE emp SET ename = ? WHERE empno = ? "). pstmt. Supply values for the variables. .executeUpdate().33 Copyright © 2009. Execute the statement. pstmt.executeUpdate().executeQuery(). 2. pstmt.setInt(2.setString(1. value). empNo). PreparedStatement pstmt = conn.setXXX(index. pstmt.

34 Copyright © 2009. Oracle. • • 15 . Can reside on a remote server or on a local desktop machine. Can be thought of as a factory for connections to the particular data source that the DataSource instance represents. . All rights reserved.What Is a DataSource? A DataSource object: • • Is the representation of a data source—a facility for storing data—in the Java programming language. Can optionally be bound to Java Naming and Directory (JNDI) entities so that you can access databases by logical names for convenience and portability.

. • Connection pooling and distributed transactions are available through a DataSource object that is implemented to work with the middle-tier infrastructure. All rights reserved. Oracle.Advantages of Using a DataSource There are a number of advantages to using a DataSource object for establishing a connection to the database: • Applications do not need to hard code a driver class. 15 .35 Copyright © 2009. • Changes can be made to a data source's properties without changing application code.

Using an OracleDataSource to Connect to a Database There are three steps that must be performed to use an OracleDataSource: 1. Connect to the database via the OracleDataSource object using the getConnection() method.OracleDataSource class. Oracle. All rights reserved.36 Copyright © 2009. 3. 2.jdbc. Create an OracleDataSource object of the oracle. 15 . Set the OracleDataSource object attributes using the set methods defined in the class.pool. .

Oracle. Use the getConnection()method to obtain a logical connection instance.Maximizing Database Access with Connection Pooling • • • Use connection pooling to minimize the operation costs of creating and closing sessions. .38 Copyright © 2009. 15 . All rights reserved. Use explicit data source declaration for physical reference to the database.

.Connection Pooling Middle tier Java servlet Data source Middle-tier server code ConnectionPoolDataSource JDBC driver Database commands Database 15 . Oracle.40 Copyright © 2009. All rights reserved.

you should have learned how to: • Load and register a JDBC driver • Use the driver to connect to an Oracle database • Perform a simple SELECT statement • • • Process the results of the query by iterating through the rows of a result set Create and use a PreparedStatement object Use an OracleDataSource to connect to a database Use a pooled connection • 15 .Summary In this lesson. . Oracle. All rights reserved.43 Copyright © 2009.

Oracle.Practice 15 Overview: Using JDBC to Access the Database This practice covers the following topics: • Setting up the Java environment for JDBC • Adding JDBC components to query the database 15 .44 Copyright © 2009. All rights reserved. .

Sign up to vote on this title
UsefulNot useful