Você está na página 1de 15

A Brief Overview of the JDBC Process

Every J2EE component uses a similar process for interacting with a DBMS. This process is divided into five routines and they are

1) Loading the JDBC driver ( The JDBC driver will be loaded before the J2EE
component can connect to the DBMS) 2) Connecting to the DBMS (J2EE component will be connected to the DBMS) 3) Creating and Executing a statement (Sending a SQL query to the DBMS for processing) 4) Processing data returned by the DBMS 5) Terminating the connection with the DBMS

DATABASE CONNECTION
Before a J2EE component connects to a DBMS, using Class.forName() method The JDBC driver for that DBMS must be loaded into the JVM and registered with the DriverManager. Class.forName() method throws a ClassNotFoundException if an error occurs when loading the JDBC driver. Errors are trapped using the catch{} block whenever the JDBC driver is being loaded. Code for loading the driver & catch any exceptions that might be thrown during the process.
try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); } catch (ClassNotFoundException error) { System.err.println(Unable to load the JDBC/ODBC bridge.+ error.getMessage()); System.exit(1); }

After the JDBC driver is successfully loaded and registered, the J2EE component must connect to the database. The data source that the J2EE component will connect to is defined using the URL format. The URL consists of three parts. These are
jdbc: it indicates that the JDBC protocol is to be used to read the URL <subprotocol>: it is the JDBC driver name <subname>: it is the name of the database

getConnection() method:
It is one of the methods of the DriverManager class It is used to establish a connection with the database and it has three versions
getConnection(String url) : It tries to establish the connection to a given database URL and this can be used when DBMS grants access to a database to anyone. getConnection(String url,String user,String password): it tries to establish the connection to a given database URL and this can be used when DBMS limits access to authorized users and require the J2EE component to supply a used ID and password

getConnection(String url,Properties info): it tries to establish connection to a given database URL and info is an object of Properties class. This method is used to access a database which is stored in a text file. This method returns an object of Connection if access is granted otherwise it throws a SQLException.

Code for connecting to a database using a usre ID and password String url = jdbc:odbc:CustomerInformation; String userID= jim; String password= keogh; Statement DataRequest; Connection Db; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Db=DriverManager.getConnection(url,userID,password); } catch (ClassNotFoundException error) { System.err.println(Unable to load the JDBC/ODBC bridge. + error); System.exit(1); } Catch (SQLException error) { System.err.println(Cannot connect to the database. + error); System.exit(2); }

TimeOut: Competition to use the same database is a common occurrence in the J2EE environment and can lead to performance degradation of a J2EE application. This can be overcome by using the following two methods of DriverManager class public static void DriverManager.setLoginTimeout(int seconds) : it can be used by the J2EE component to establish the max. time the DriverManager waits for a response from a DBMS before timing out. public static int DriverManager.getLoginTimeout() : it is used to retrieve from the DriverManager the max. time the DriverManager is set to wait until it times out. It returns an int that represents seconds. Associating the JDBC/ODBC bridge with the database: Steps for creating an association between the database and the JDBC/ODBC bridge using the ODBC Data Source Administrator.

Creating and Executing a statement (Sending a SQL query to the DBMS for processing) Statement Objects: There are three types of Statement Objects to execute the query and they are

1) Statement Object ( Executes a query immediately) 2) PreparedStatement objects ( Executes a compiled query) 3) CallableStatement objects ( Executes stored procedures)

The Statement object


This is used whenever a J2EE component needs to immediately execute a query without first having the query compiled. This contains three methods to execute the queries and they are 1) executeQuery() : it is passed the query as an argument. The query is then transmitted for processing. It returns one ResultSet object that contains rows, columns, and metadata. The ResultSet object also contains methods that are used to manipulate data in the ResultSet. It throws SQLException error if the query is not understood by the DBMS 2) executeUpdate() : it is used to execute queries that contain UPDATE and DELETE SQL statements, which changes values in a row and removes a row respectively. It returns an integer indicating the number of rows that were updated by the query. 3) execute() : it is used when there may be multiple results returned.

An example program for executeQuery()


String url = jdbc:odbc:CustomerInformation; String userID= jim; String password= keogh; Statement DataRequest; ResultSet Results; Connection Db; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Db=DriverManager.getConnection(url,userID,password); } catch (ClassNotFoundException error) { System.err.println(Unable to load the JDBC/ODBC bridge. + error); System.exit(1); } Catch (SQLException error) { System.err.println(Cannot connect to the database. + error); System.exit(2); } try { String query = SELECT * FROM Customers; DataRequest = Db.createStatement(); Results = DataRequest.executeQuery(query); DataRequest.close(); } catch (SQLException error) { System.err.println (SQL error. + error); System.exit(3); } Db.close();

The PreparedStatement Object


It is used to execute the precompiled queries. In this, query is constructed similar to queries seen in the previous program but a question mark is used as a placeholder for a value that is inserted into the query after the query is compiled. It is this value that changes each time the query is executed. Example program for PreparedStatement Object: Objective: Returning all customer info. Where the customer number equals the customer number specified in the query

An example program for PreparedStatement object String url = jdbc:odbc:CustomerInformation; String userID= jim; String password= keogh; ResultSet Results; Connection Db; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Db=DriverManager.getConnection(url,userID,password); } catch (ClassNotFoundException error) { System.err.println(Unable to load the JDBC/ODBC bridge. + error); System.exit(1); } Catch (SQLException error) { System.err.println(Cannot connect to the database. + error); System.exit(2); } try { String query = SELECT * FROM Customers WHERE CustNumber = ?; PreparedStatement pstatement = Db.preparedStatement(query); pstatement.setString(1,123); Results = pstatement.executeQuery(); pstatement.close(); } catch (SQLException error) { System.err.println (SQL error. + error); System.exit(3); } Db.close();

Advantage of PreparedStatement Object: The query is precompiled once and the setxxx() method called as needed to change the specified values of the query without having to recompile the query. It also has an execute() and executeUpdate() methods. The precompiling is performed by the DBMS and is referred to as late binding

The CallableStatement Object


It is used to call a stored procedure. A stored procedure is a black of code and is identified by a unique name. The stored procedure is executed by invoking the name of the stored procedure. The type and style of code depends on the DBMS vendor and can be written in PL/SQL, Transact-SQL, C or another programming language. It uses 3 types of parameters when calling a stored procedure and these 3 parameters are IN, OUT and INOUT IN : This parameter contains any data that needs to be passed to the stored procedure and whose value is assigned using the setxxx() method. OUT: This parameter contains the value returned by the stored procedures if any. This must be registered using the registerOutParameter() method and then later retrieved by the J2EE component using the getxxx() method. INOUT: This is a single parameter that is used to both pass information to the stored procedure and retrieve information from a stored procedure. Example program for CallableStatement Object: Objective: illustrating how to call a stored procedure and retrieve a value returned by the stored procedure

An example program for CallableStatement object String url = jdbc:odbc:CustomerInformation; String userID= jim; String password= keogh; String lastOrderNumber; Connection Db; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Db=DriverManager.getConnection(url,userID,password); } catch (ClassNotFoundException error) { System.err.println(Unable to load the JDBC/ODBC bridge. + error); System.exit(1); } Catch (SQLException error) { System.err.println(Cannot connect to the database. + error); System.exit(2); } try { String query = { CALL LastOrderNumber (?) } ; CallableStatement cstatement = Db.prepareCall(query); cstatement.registerOutParameter(1,Types.VARCHAR); cstatement.execute(); lastOrderNumber = cstatement.getString(1); cstatement.close(); } catch (SQLException error) { System.err.println (SQL error. + error); System.exit(3); } Db.close();

Você também pode gostar