+ All Categories

JDBC

Date post: 15-Nov-2014
Category:
Upload: mohanraop
View: 294 times
Download: 1 times
Share this document with a friend
Popular Tags:
20
© Accenture 2005 All Rights Reserved Course Code #Z16325 ATS Application Programming: ATS Application Programming: Java Programming Java Programming 9.2 Java 9.2 Java Database Database Connectivity Connectivity
Transcript
Page 1: JDBC

© Accenture 2005 All Rights Reserved Course Code #Z16325

ATS Application Programming: Java ATS Application Programming: Java ProgrammingProgramming

9.2 Java Database 9.2 Java Database ConnectivityConnectivity

Page 2: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

22

© Accenture 2005 All Rights Reserved

Understand the JDBCUnderstand the JDBC Understand the steps of the JDBC:Understand the steps of the JDBC:

1.) Importing packages1.) Importing packages

2.) Opening a connection to a database2.) Opening a connection to a database

3.) Working with different types of database drivers 3.) Working with different types of database drivers

4.) Querying the database4.) Querying the database• Creating a Statement object to perform a query ResultSet or Creating a Statement object to perform a query ResultSet or

create a PreparedStatementcreate a PreparedStatement• Executing a query and return a ResultSet objectExecuting a query and return a ResultSet object• Differentiating between a Statement and a PreparedStatementDifferentiating between a Statement and a PreparedStatement

ObjectivesObjectives

Page 3: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

33

© Accenture 2005 All Rights Reserved

Objectives Objectives (continued)(continued)

(Steps of the JDBC, continued)(Steps of the JDBC, continued)

5.) Processing a ResultSet5.) Processing a ResultSet

6.) Closing the ResultSet and Statement6.) Closing the ResultSet and Statement

7.) Importance of closing the connection7.) Importance of closing the connection Understand a JBDC row set.Understand a JBDC row set.

Page 4: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

44

© Accenture 2005 All Rights Reserved

What is JDBC?What is JDBC?JDBC (Java Database Connectivity)JDBC (Java Database Connectivity)

A standard Java interface for connecting from A standard Java interface for connecting from Java to relational databases. The JDBC Java to relational databases. The JDBC standard was defined by Sun Microsystems, standard was defined by Sun Microsystems, allowing individual providers to implement allowing individual providers to implement and extend the standard with their own JDBC and extend the standard with their own JDBC driversdrivers

Page 5: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

55

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC1.1. Import PackagesImport Packages

Import statements at the beginning of your program:Import statements at the beginning of your program:

import java.sql.Connection;import java.sql.Connection;

import java.sql.SQLException;import java.sql.SQLException;

oror

import java.sql.*;import java.sql.*;

Import the ff. Oracle packages when you want to access the Import the ff. Oracle packages when you want to access the extended functionality provided by the Oracle drivers.extended functionality provided by the Oracle drivers.

import oracle.jdbc.pool.OracleOCIConnectionPool;import oracle.jdbc.pool.OracleOCIConnectionPool;

oror

import oracle.jdbc.*;import oracle.jdbc.*;

Page 6: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

66

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC2. Open a Connection to a Database2. Open a Connection to a Database

A call to this method creates an object instance of theA call to this method creates an object instance of the java.sql.Connectionjava.sql.Connection class.class.

The The getConnection()getConnection() method is an overloaded method that takes method is an overloaded method that takes Three parameters, one each for the URL, username, and passwordThree parameters, one each for the URL, username, and password Only one parameter for the database URL. In this case, the URL contains the Only one parameter for the database URL. In this case, the URL contains the

username and passwordusername and password

The ff. lines of code illustrate using the The ff. lines of code illustrate using the getConnection()getConnection() method: method:

Connection conn = DriverManager.getConnection(Connection conn = DriverManager.getConnection(URLURL, , username, username, passwdpasswd); ); OrOr

Connection conn = DriverManager.getConnetion(Connection conn = DriverManager.getConnetion(URLURL););

where where URL, username and passwordURL, username and password are of are of StringString data types. data types.

Page 7: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

77

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBCOpening a Connection using the Oracle JDBC OCI:Opening a Connection using the Oracle JDBC OCI:

When using the OCI driver, the database can be specified When using the OCI driver, the database can be specified using the TNSNAMES entry in the tnsnames.ora.file. For using the TNSNAMES entry in the tnsnames.ora.file. For example, to connect to a database on a particular host as user example, to connect to a database on a particular host as user oratest with password oratest that has a TNSNAMES entry of oratest with password oratest that has a TNSNAMES entry of oracle.world, use the following code:oracle.world, use the following code:

Connection conn = Connection conn = DriverManager.getConnection(“jdbc:oracle:oci9:@orDriverManager.getConnection(“jdbc:oracle:oci9:@oracle.world”, “oratest”, “oratest”);acle.world”, “oratest”, “oratest”);

Page 8: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

88

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC3. 3. Querying the DatabaseQuerying the Database

Querying the database involves the following steps:Querying the database involves the following steps:

Creating a Statement ObjectCreating a Statement ObjectThis is to instantiate objects that run the query against the database to which they are connected. This is to instantiate objects that run the query against the database to which they are connected. This is done by the This is done by the createStatement()createStatement() method of the method of the conn conn Connection object created Connection object created above. A call to this method creates an object instance of the Statement class. The ff. line of code above. A call to this method creates an object instance of the Statement class. The ff. line of code illustrates this:illustrates this:

Statement sql_stmt = conn.createStatement();Statement sql_stmt = conn.createStatement();

OrOr

Creating a PreparedStatementCreating a PreparedStatementA PreparedStatement is associated as a channel with a connection and a compiled SQL statement. A PreparedStatement is associated as a channel with a connection and a compiled SQL statement. PreparedStatements are also created with a Connection method. The following snippet shows how PreparedStatements are also created with a Connection method. The following snippet shows how to create a parameterized SQL statement with three input parameters:to create a parameterized SQL statement with three input parameters:

PreparedStatement prepareUpdatePrice = PreparedStatement prepareUpdatePrice = conn.prepareStatement( "UPDATE Sells SET price = ? WHERE bar = ? conn.prepareStatement( "UPDATE Sells SET price = ? WHERE bar = ? AND beer = ?"); AND beer = ?");

Page 9: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

99

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC

Executing the Query and Returning a ResultSetExecuting the Query and Returning a ResultSet

This is done by using the This is done by using the executeQuery()executeQuery() method method of the of the StatementStatement object. A call to this method takes object. A call to this method takes as parameter a SQL SELECT statement and returns a as parameter a SQL SELECT statement and returns a JDBC JDBC ResultSetResultSet object. The ff. line of code object. The ff. line of code illustrates this using the illustrates this using the sql_stmtsql_stmt object created object created above:above:

ResultSet rset = sql_stmt.executeQuery ResultSet rset = sql_stmt.executeQuery

(“SELECT empno, ename, sal, deptno FROM (“SELECT empno, ename, sal, deptno FROM emp ORDER BY ename”);emp ORDER BY ename”);

Page 10: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1010

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC4. Process the Result Set4. Process the Result Set

Once the query has been executed, there are two steps to be Once the query has been executed, there are two steps to be carried out:carried out:• Processing the output resultSet to fetch the rowsProcessing the output resultSet to fetch the rows

next()next() method of the method of the ResultSetResultSet object object• Retrieving the column values of the current rowRetrieving the column values of the current row

getXXX()getXXX() methods of the JDBC rset object methods of the JDBC rset object

Here Here getXXX()getXXX() corresponds to the corresponds to the getInt(), getString()getInt(), getString() etc etc with XXX being replaced by a Java datatypewith XXX being replaced by a Java datatype

while (rset.next())while (rset.next())

System.out.println (rset.getString(“ename”));System.out.println (rset.getString(“ename”));

Page 11: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1111

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC5. Closing the ResultSet and Statement5. Closing the ResultSet and Statement

Once the Once the ResultSetResultSet and and StatementStatement objects have been objects have been used, they must be closed explicitly. This is done by calls used, they must be closed explicitly. This is done by calls to the to the close()close() method of the method of the ResultSetResultSet and and StatementStatement classes. The ff. code illustrates this: classes. The ff. code illustrates this:

rset.close();rset.close();

sql_stmt.close();sql_stmt.close();

If not closed explicitly, there are two disadvantagesIf not closed explicitly, there are two disadvantages :: Memory leaks can occurMemory leaks can occur Maximum Open cursors can be exceededMaximum Open cursors can be exceeded

Page 12: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1212

© Accenture 2005 All Rights Reserved

Steps in JDBCSteps in JDBC

6. Closing the Connection6. Closing the Connection

The last step is to close the database connection after The last step is to close the database connection after importing the packages and loading the JDBC importing the packages and loading the JDBC drivers. This is done by a call to the drivers. This is done by a call to the close()close() method method of the Connection class.of the Connection class.

The ff. line of code does this:The ff. line of code does this:

conn.close();conn.close();

Page 13: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1313

© Accenture 2005 All Rights Reserved

package com.jds.architecture.service.dbaccess;package com.jds.architecture.service.dbaccess;import java.sql.Connection;import java.sql.Connection;import java.sql.SQLException;import java.sql.SQLException;import javax.sql.ConnectionPoolDataSource;import javax.sql.ConnectionPoolDataSource;import oracle.jdbc.pool.OracleOCIConnectionPool;import oracle.jdbc.pool.OracleOCIConnectionPool;

public class OracleOCIDBAccess implements public class OracleOCIDBAccess implements DBAccessInterface {DBAccessInterface {private static String JDBC_URL = private static String JDBC_URL = "jdbc:oracle:oci:@ORCL";"jdbc:oracle:oci:@ORCL";private static String USER_ID = "hruser";private static String USER_ID = "hruser";private static String PASSWORD = "hruser";private static String PASSWORD = "hruser";

OracleOCIConnectionPool cpool = null;OracleOCIConnectionPool cpool = null;/**/** * constructor* constructor * @throws DBAccessException* @throws DBAccessException */*/

protected OracleOCIDBAccess() throws DBAccessException {protected OracleOCIDBAccess() throws DBAccessException {dbConnect();dbConnect();

}}

ExampleExample

Import Packages

Declaration

OCI driver connection pooling functionality,provided by the OracleOCIConnectionPool class,

is part of the JDBC client.

Page 14: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1414

© Accenture 2005 All Rights Reserved

public void dbConnect() throws DBAccessException {public void dbConnect() throws DBAccessException {try{try{

cpool = new OracleOCIConnectionPool();cpool = new OracleOCIConnectionPool();cpool.setURL(JDBC_URL);cpool.setURL(JDBC_URL);cpool.setUser(USER_ID);cpool.setUser(USER_ID);cpool.setPassword(PASSWORD);cpool.setPassword(PASSWORD);} catch (SQLException e) {} catch (SQLException e) {throw new DBAccessException throw new DBAccessException

("dbaccess.sql.connection.exception",e.getCause(),("dbaccess.sql.connection.exception",e.getCause(),DBAccessException.ERROR, true);DBAccessException.ERROR, true);

} catch (Exception e) {} catch (Exception e) {e.printStackTrace();e.printStackTrace();throw new DBAccessException throw new DBAccessException

("dbaccess.oracle.connection.exception",e.getCause(),("dbaccess.oracle.connection.exception",e.getCause(),DBAccessException.ERROR, true);DBAccessException.ERROR, true);

}}}}

Cont…Cont…Initialize the Database Connection

Page 15: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1515

© Accenture 2005 All Rights Reserved

/**/** * Returns database connection from oci connection * Returns database connection from oci connection poolpool * @return Connection - database connection* @return Connection - database connection */*/public Connection getConnection() throws public Connection getConnection() throws DBAccessException {DBAccessException {

Connection conn = null;Connection conn = null;try{try{

conn = cpool.getConnection();conn = cpool.getConnection();} catch(SQLException e) {} catch(SQLException e) {

throw new DBAccessException throw new DBAccessException ("dbaccess.getconnection.sql.exception",("dbaccess.getconnection.sql.exception",

e.getCause(), DBAccessException.ERROR, e.getCause(), DBAccessException.ERROR, true);true);

}}return conn;return conn;

}}}}

Cont…Cont…

Open a Connection To a Database

Page 16: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1616

© Accenture 2005 All Rights Reserved

Row SetRow SetA JDBC A JDBC RowSetRowSet object holds tabular data in a way that makes it more object holds tabular data in a way that makes it more flexible and easier to use than a result set. A flexible and easier to use than a result set. A Row Set Row Set is an object which is an object which encapsulates a set of rows. encapsulates a set of rows.

Kinds of RowSet ObjectsKinds of RowSet Objects

ConnectedConnected RowSet object uses a driver based on JDBC technology (“JDBC RowSet object uses a driver based on JDBC technology (“JDBC Driver”) to make a connection to a relational database and maintains that Driver”) to make a connection to a relational database and maintains that connection throughout its life span.connection throughout its life span.

Only one of the standard Only one of the standard RowSetRowSet implementations is a connected implementations is a connected RowSetRowSet: : JdbcRowSetJdbcRowSet. Being always connected to a database, it is very similar to a . Being always connected to a database, it is very similar to a ResultSetResultSet object and is often used as a wrapper to make an otherwise object and is often used as a wrapper to make an otherwise nonscrollable and read-only ResultSet object scrollable and updatable.nonscrollable and read-only ResultSet object scrollable and updatable.

You can create a You can create a JdbcRowSetJdbcRowSet object in two ways: object in two ways: By using the reference implementation constructor that takes a ResultSet objectBy using the reference implementation constructor that takes a ResultSet object By using the reference implementation default constructorBy using the reference implementation default constructor

Statement stmt = con.createStatement();Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(select * from COFFEES);ResultSet rs = stmt.executeQuery(select * from COFFEES);JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);

Page 17: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1717

© Accenture 2005 All Rights Reserved

Row SetRow SetUsing the Default ConstructorUsing the Default ConstructorThe following line of code creates an empty The following line of code creates an empty JdbcRowSetJdbcRowSet object. object.JdbcRowSet jdbcRs2 = new JdbcRowSetImpl();JdbcRowSet jdbcRs2 = new JdbcRowSetImpl();

DisconnectedDisconnected RowSetRowSet objects make a connection to a data source only objects make a connection to a data source onlyto read in data from a to read in data from a ResultSetResultSet object or to write data back to the data object or to write data back to the data source.source.

The other four implementations are disconnected The other four implementations are disconnected RowSetRowSet implementations. implementations. 1.1. A A CachedRowSetCachedRowSet object has all the capabilities of a object has all the capabilities of a JdbcRowSetJdbcRowSet object plus it object plus it

can also do the following:can also do the following: Obtain a connection to a data source and execute a queryObtain a connection to a data source and execute a query Read the data from the resulting Read the data from the resulting ResultSetResultSet object and object and

populate itself with that datapopulate itself with that data Manipulate data and make changes to data while it is Manipulate data and make changes to data while it is

disconnecteddisconnected Reconnect to the data source to write changes back to itReconnect to the data source to write changes back to it Check for conflicts with the data source and resolve those Check for conflicts with the data source and resolve those

conflictsconflicts

Page 18: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1818

© Accenture 2005 All Rights Reserved

Row SetRow SetYou can create a new You can create a new CachedRowSet CachedRowSet object in two different ways:object in two different ways:

By using the default constructorBy using the default constructorCachedRowSet crs = new CacheRowSetImpl();CachedRowSet crs = new CacheRowSetImpl();

By Passing a SyncProvider implementation to the constructorBy Passing a SyncProvider implementation to the constructorCachedRowSet crs2 = CachedRowSet crs2 = CachedRowSetImpl(“com.fred.providers.HighAvailabiCachedRowSetImpl(“com.fred.providers.HighAvailabilityProvider”);lityProvider”);

2. A 2. A WebRowSetWebRowSet object has all the capabilities of a object has all the capabilities of a CachedRowSetCachedRowSet object object plus it can also do the following:plus it can also do the following:

Write itself as an XML documentWrite itself as an XML document Read an XML document that describes a Read an XML document that describes a WebRowSetWebRowSet object objectWebRowSet pricelist = new WebRowSetImpl();WebRowSet pricelist = new WebRowSetImpl();

3. A3. A JoinRowSetJoinRowSet object has all the capabilities of a object has all the capabilities of a WebRowSetWebRowSet object object (and therefore also a (and therefore also a CachedRowSetCachedRowSet object) plus it can also do the object) plus it can also do the following:following:

Form the equivalent of an SQL JOIN without having to connect to a data Form the equivalent of an SQL JOIN without having to connect to a data sourcesourceJoinRowSet jrs = new JoinRowSetImpl();JoinRowSet jrs = new JoinRowSetImpl();

Page 19: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

1919

© Accenture 2005 All Rights Reserved

Row SetRow Set4. 4. A A FilteredRowSetFilteredRowSet object likewise has all the capabilities of a object likewise has all the capabilities of a WebRowSetWebRowSet object (and therefore also a object (and therefore also a CachedRowSetCachedRowSet object) plus object) plus it can also do the following:it can also do the following:

Apply filtering criteria so that only selected data is visible. This is equivalent to Apply filtering criteria so that only selected data is visible. This is equivalent to executing a query on a executing a query on a RowSetRowSet object without having to use a query language or object without having to use a query language or connect to a data source.connect to a data source.

FilterRowSet frs = new FilteredRowSetImpl();FilterRowSet frs = new FilteredRowSetImpl();

This object is initialized with the following:This object is initialized with the following: The high end of the range within which values must fallThe high end of the range within which values must fall The low end of the range within which values must fallThe low end of the range within which values must fall The column name or column number of the value that must fall within the The column name or column number of the value that must fall within the

range of values set by the high and low boundariesrange of values set by the high and low boundaries

Filter1 range = new Filter(1000, 10999, Filter1 range = new Filter(1000, 10999, “STORE_ID”);“STORE_ID”);

The next line of code sets The next line of code sets rangerange as the filter foras the filter for frsfrs..frs.setFilter(range);frs.setFilter(range);

Page 20: JDBC

©2004 Accenture All Rights Reserve©2004 Accenture All Rights Reserved.d.

2020

© Accenture 2005 All Rights Reserved

Questions:Questions:


Recommended