Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

Search: 

  Tutorial: Create your own type 3 JDBC driver, Part 3

Create your own type 3 JDBC driver, Part 3

Tutorial Details:

Create your own type 3 JDBC driver, Part 3
Create your own type 3 JDBC driver, Part 3
By: By Sunil Kumar and Nitin Nanda
Enhance the custom JWDriver with advanced logging, connection pooling, and Predefined Data Sets
rchitecturally, type 3 JDBC (Java Database Connectivity) drivers prove flexible enough that you can easily add enhancements. In Parts 1 and 2 of this three-part series, you learned how to create a custom type 3 JDBC driver, named JWDriver, that employed RMI (Remote Method Invocation) to communicate with the middle tier. In this article, the last of the series, we demonstrate how to enhance JWDriver's functionality with three new features:
SQL statement logging for diagnosis
Database connection pooling for faster connection retrieval
Predefined Data Sets (PDS) for improved network latency
Read the whole "Create Your Own Type 3 JDBC Driver" series:
Part 1: Connect your Java applications to databases?the easy way
Part 2: Compile, deploy, and access data using your custom-built JDBC driver
Part 3: Enhance the custom JWDriver with advanced logging, connection pooling, and Predefined Data Sets
Let's examine each new feature in turn.
Note: You can download this article's source code from Resources .
Feature 1: SQL statement logging for diagnosis
Business applications typically contain numerous SQL data-manipulation and data-retrieval statements to implement various business features. You sometimes may wish to log for later analysis such SQL statements as they execute on the database server. Other uses for logging SQL statements include finding, during the development life cycle, performance bottlenecks from slow SQL statements, or tracking hard-to-find bugs in a complex business transaction containing multiple SQL statements.
To add SQL statement logging capability to JWDriver, begin by adding a new class, DriverLog , in the driver's middle tier. That class provides the interface to write SQL statements to a predefined file. Each executed SQL statement passes through the remote statement class's executeQuery() and executeUpdate() methods in the middle tier, so the two methods contain the call to the DriverLog methods to log the SQL statements.
Let's now see DriverLog 's implementation and its use in the driver's remote statement class.
The DriverLog class
The SQL statement logging occurs in the Web server, where the driver's middle tier is deployed. Create DriverLog under the middle tier's com.jw.server package. To handle concurrent clients, DriverLog employs the Singleton pattern by making its constructor private to ensure only one instance. The getInstance() method returns the DriverLog reference. The public logQuery() method actually logs the SQL statements into the log file.
The DriverLog constructor opens the C:\TEMP\JWDriver.log disk file for logging SQL statements. The constructor uses the PrintWriter and FileWriter classes to access the JWDriver.log file. The constructor also opens JWDriver.log in append mode. Here's the constructor's code:
private DriverLog()
{
try
{
logFileWriter = new FileWriter(logFile,true);
logPrintWriter = new PrintWriter(logFileWriter,true);
}
catch(Exception ex)
{
logFileWriter = null;
logPrintWriter = null;
ex.printStackTrace();
}
}
Since we've marked the DriverLog class constructor as private, the class is accessed via a public getInstance() method. The getInstance() method always returns the same DriverLog class reference. The single DriverLog instance is maintained in a static class variable singleLogInstance and created only once as soon as the getInstance() method is first accessed:
public static DriverLog getInstance(){
if(singleLogInstance == null)
singleLogInstance = new DriverLog();
return singleLogInstance;
}
The remote statement calls the public logQuery() method to log SQL statements into the file. The logQuery() method, which logs the SQL statements with the current date and time, includes a synchronized block that ensures the concurrent clients access the log file one at a time. logQuery() logs SQL statements only if you've switched the logging on, which you'll see in the next section. Here's the code:
public void logQuery(String query){
try{
if(RemoteDriverImpl.queryLog == 1){
if(logPrintWriter != null){
synchronized(logPrintWriter){
Date theDate = new Date();
String fullMsg = "Logged at:" + theDate.toString();
logPrintWriter.println("----------------------------------
--------------------------------------------------------");
logPrintWriter.println(fullMsg);
logPrintWriter.println(query);
}
}
}
}
catch(Exception ex){}
}
Log SQL statements in the server
The SQL statements get logged in the driver middle-tier machine in a JWDriver.log file. Switch on SQL statement logging by setting QueryLog to 1 in the DriverSettings.properties file. (You can switch logging back off by setting QueryLog to 0.)
The driver client tier passes the SQL statement to the middle tier via IRemoteStatement for execution in the database server. The executeQuery() and executeUpdate() methods in RemoteStatementImpl then call the logQuery() method to log the SQL statements before execution:
public IRemoteResultSet executeQuery(String Query) throws RemoteException,SQLException{
// Log the SQL statement
DriverLog.getInstance().logQuery(Query);
ResultSet rs = sqlStatment.executeQuery(Query);
RemoteResultSetImpl remoteRs = new RemoteResultSetImpl(rs);
return (IRemoteResultSet)remoteRs;
}
public int executeUpdate(String Query) throws RemoteException,SQLException{
// Log the SQL statement
DriverLog.getInstance().logQuery(Query);
return sqlStatment.executeUpdate(Query);
}
Feature 2: Database connection pooling for faster connection retrieval
Establishing a database connection to execute a SQL statement always takes time. To increase an application's performance, you can cache database connections, a feature you can easily implement in JWDriver. Whenever a connection request to the database server comes from the middle tier to serve the client application request, the connection returns from the pool. When the client application closes a connection, the connection in the middle tier returns to the pool so that it could serve other client requests. All that happens with the client unaware whether connection pooling is implemented in the middle tier.
We will cover the following topics to discuss JWDriver's connection-pooling support:
The connection pool
Initializing the connection pool
Retrieving the connection from the pool
Returning the connection to the pool
The connection pool
The ConnectionPool class, created in the driver middle tier under the com.jw.server package, implements the connection pool. ConnectionPool employs the Singleton pattern to handle the concurrent clients by making its constructor private to ensure only one instance. The getInstance() method returns a ConnectionPool reference. ConnectionPool provides the addConnection() method for adding the connections to the pool during the server's launch. The included getConnection() method gets the connection from the pool.
The constructor creates the empty stack that will hold the connections as:
private ConnectionPool()
{
connectionPool = new Vector();
}
ConnectionPool is accessed via the public getInstance() method, which always returns the same reference of the ConnectionPool class. The single ConnectionPool instance is maintained in a static class variable connectionPoolInstance . The single connectionPoolInstance instance is created only once when the getInstance() method is first accessed. The code for the getInstance() method is given below:
public static ConnectionPool getInstance()
{
if(connectionPoolInstance == null)
connectionPoolInstance = new ConnectionPool();
return connectionPoolInstance;
}
The ConnectionPool class keeps the pooled database connections in a stack implemented by the Vector object. ConnectionPool provides two methods? addConnection() and getConnection() ?to access the connection pool stack. These methods push and pop the connection from the stack, respectively:
public synchronized void addConnection(Connection con){
// Add the JDBC-ODBC bridge connection to the pool
connectionPool.addElement(con);
}
public synchronized Connection getConnection(){
Connection con = null;
if(connectionPool.size() > 0){
con = (Connection)connectionPool.lastElement();
connectionPool.removeElementAt(connectionPool.size() - 1);
}
return con;
}
Initialize the connection pool
The connection pool initializes when JWDriver's RMI server starts up. The RemoteDriverImpl class creates the JDBC-ODBC (Open Database Connectivity) bridge connections and adds them into the pool:
private void initializeConnectionPool(){
String URL="jdbc:odbc:"+DSN;
for(int i = 0; i < connectionPoolSize; i++){
Connection sqlCon = DriverManager.getConnection(URL,dsUser,dsPassword);
ConnectionPool.getInstance().addConnection(sqlCon);
}
}
You can configure the connection pool's size and change it by setting the ConnectionPoolSize value in the DriverSettings.properties file. The setting below specifies the connection pool size as 5:
ConnectionPoolSize=5
Retrieve the connection from the pool
Whenever a client program requests a connection, JWDriver's client tier delegates the request to the middle tier. The RemoteDriverImpl 's getConnection() method then gets the connection from the connection pool. If the connection pool has no free connection, an exception throws:
public IRemoteConnection getConnection() throws RemoteException,SQLException{
Connection con = ConnectionPool.getInstance().getConnection();
if(con == null)
throw new SQLException("All connections in the driver Connection Pool are in use.");
RemoteConnectionImpl ConnectionInstance = new RemoteConnectionImpl(con);
return (IRemoteConnection)ConnectionInstance;
}
Figure 1 shows the sequence diagram for retrieving the connection from the pool.
Figure 1. Get a connection from t


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Create your own type 3 JDBC driver, Part 3

View Tutorial:
Create your own type 3 JDBC driver, Part 3

Related Tutorials:

Displaying 1 - 50 of about 3755 Related Tutorials.

Product Components of JDBC
. The JDBC API. 2. The JDBC Driver Manager. 3. The JDBC Test Suite. 4. The JDBC..., also known as JDBC type 1 driver is a  database driver that utilize....  JDBC application programmming interface is a  part of the Java
 
JDBC Driver and Its Types
, also called Type 2. JDBC-Net, pure Java driver, also called Type 3... The JDBC type 3 driver, also known as the network-protocol driver is a database driver.... Type 1 Driver- the JDBC-ODBC bridge The JDBC type 1 driver, also
 
Driver Manager Class
; The JDBC Driver Manager The JDBC Driver Manager... to a JDBC driver. Usually  Driver Manager is the backbone of the JDBC... of managing the different types of JDBC database driver running on an application
 
JDBC Components
important part of the JDBC architecture. 3. JDBC Test Suite The JDBC driver test... statements and retrieve results and updation to the database. The JDBC API is part of the Java platform, it includes the Java Standard Edition. 2. JDBC Driver
 
Create Your Own Package
Create Your Own Package Create Your Own Package... things: Create a directory "mypackage" . Save the  source file... the class "HelloWorld" then type the following command shown
 
Difficult Interview Questions Page -3
by your own mouth. This is a great way to brag about yourself through someone... Difficult Interview Questions Page -3 Difficult Interview Questions Page -3       
 
First Step towards JDBC!
calls. Type 3: JDBC-Net Pure Java Driver Type.... These are: Type 1: JDBC-ODBC Bridge Driver... JDBC-ODBC bridge is example of type 1 driver. Type 2: Native
 
JDO UNPLUGGED - PART II
UNPLUGGED - PART II JDO UNPLUGGED - PART II... : It is the sun's reference implementation of JDO specification. 3. btree.jar... this jar. By using this jar, we can create JDO in any implementation
 
Introduction to the JDBC
. Type 3: JDBC-Net Pure Java Driver Type 3... JDBC driver types. These are: Type 1: JDBC-ODBC Bridge Driver The first type of JDBC driver
 
Jdbc batch
Jdbc batch Jdbc batch     ...;         JDBC is simply a Java... to interact your Java Application in your front end with the backend. The backend can
 
Understanding the JDBC Architecture
2 JDBC Architecture Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure Java drivers that use a proprietary network... statements ------> databases. Type 3 JDBC Architecture Type 4 Java
 
The Ubuntu Linux 6.04 Alpha 3 has been released
The Ubuntu Linux 6.04 Alpha 3 has been released The Ubuntu Linux 6.04 Alpha 3 has been released The Dapper Drake... improvements. This week brings us Flight 3, the third alpha release of Ubuntu 6.04
 
JDO UNPLUGGED - PART 1
UNPLUGGED - PART I JDO UNPLUGGED - PART I... JDBC and EJB with CMP and BMP. Also there are a number of ORM tools like... it differs from the rest of the technologies. When we use JDBC, we have to manage
 
Jdbc access database
your driver is loaded ,you can connect the front end of the Java application... the exception. 3)st = con.createconnection( ) -This is used to create Sql object... Jdbc access database Jdbc access database
 
Java Interview Questions 3
Java Interview Questions page 3     ..., telling the object serialization tools that your class is serializable... to implement these two methods in order to make your class externalizable
 
JDBC, JDBC Tutorial, JDBC Tutorials
, JDBC Driver Manager, The JDBC Test Suite and JDBC-ODBC Bridge.  ... a uniform interface for accessing various relational databases. JDBC is a core part....      JDBC Driver and Its Types   
 
JDBC Versions
JDBC Driver and Its Types JDBC Versions...). The JDBC 1.2 API. 3). The JDBC 2.0 Optional Package API. 4). The JDBC 2.1...- loading of JDBC driver class. 2). Connection management enhancements
 
Description of EJB 3
Description of EJB 3 Description of EJB 3... annotations supported by JDK 5.0.  EJB 3 Training Summary ... the Enterprise JavaBeans (EJB 3) technology.  This is a comprehensive
 
What is JDBC?
with  the JDBC Driver Manager that is used as a connection factory... such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc... What is JDBC? What is JDBC?  
 
Java Hibernate 3 Programmer
Java Spring Framework Programmer Java Hibernate 3...;     Position Vacant: Java Hibernate 3...: Hibernate, Hibernate 3, Java, Programming, Coding, Unit Testing  Contact
 
Jdbc ConnectionUrl
Jdbc ConnectionUrl Jdbc ConnectionUrl  ...; In this Tutorial we want to describe you a code that helps you to understand Jdbc... Driver - The second step is the loading of a driver class that invokes
 
Jdbc-Odbc Connectivity
Jdbc-Odbc Connectivity Jdbc-Odbc Connectivity...;  The code illustrates an example from JDBC-ODBC Connectivity... ( ) is to load a driver by calling class.forName( ) by accepting driver class
 
Jdbc autocommit
Jdbc autocommit Jdbc autocommit   ...;            Jdbc connection... In this Tutorial we want to describe you a code that helps in understanding JDBC auto commit
 
JDBC Prepared Statement Insert
JDBC Prepared Statement Insert JDBC Prepared...;    The Tutorial illustrates a program in JDBC Prepared...)Loading a driver inside the try block by calling a class.forName ( ),that accepts
 
DataScope JDBC
the jar files in a directory. Write your own classes to perform custom actions... DataScope JDBC DataScope JDBC...; DataScope is an extensible JDBC plugin for the Eclipse IDE that allows
 
JDBC Execute Query
as driver class.When a driver is loaded, you connect the front end of your Java... JdbcExecutequery JDBC Execute Query  ...; In this Tutorial we want to explain you an example from JDBC Execute query, For this we have
 
New Features in JDBC 4.0
important feature in JDBC that has relieved the developers from loading the driver..., if the JDBC Driver Provider wants to make his implementation as a Service then he... will automatically load the JDBC driver by the procedure. Moreover
 
Connecting to the Database Using JDBC and Pure Java driver
Connecting to the Database Using JDBC and Pure Java driver...; JDBC Driver... Applications and Applets. MM.MySQL Driver provide all the JDBC
 
Common Interview Questions Page -3
Common Interview Questions Page -3 Untitled Document Common Interview Questions Page -3    ... are a fresher and just completed your academics or what so ever.  Question: 6. Do
 
Create dynamic page through JSP
) ); Create your application directory named "user" in the Tomcat... { // Load JDBC driver "com.mysql.jdbc.Driver"... How to read text file in Servlets Create dynamic page
 
Difference between JDBC 3.0 & JDBC 4.0
type. Now in JDBC 4 every PreparedStatement is poolable by default. Auto- loading of JDBC driver class: In JDBC 4 invoking the getConnection...; Support for RowId data type: JDBC introduces  support for ROWID, a data
 
Jdbc-Odbc Connection
; JDBC-ODBC Connection is a JDBC driver that translates the operation in  JDBC into ODBC. For ODBC,it is a normal java application program... Jdbc-Odbc Connection Jdbc-Odbc Connection
 
JDBC connection timeout
Jdbc connection timeout JDBC connection timeout...; In this Tutorial we want to describe you a code that help you in understand JDBC connection timeout. The code include a class JDBC Connection Timeout, inside
 
Java with EJB 3
Java with EJB 3 Java with EJB 3...; Position Vacant: Java with EJB 3 Job Description  You...://www.roseindia.net  Reference ID: Java with EJB 3
 
JDBC Get Row Count
JDBC Get Row Count JDBC Get Row Count  ...; In this Tutorial we want to describe a code that make you to understand in JDBC Get Row... that help in communicating between the front end and the backend.2)Loading a driver
 
Buy Fedora Core 3 Linux CD's in India.
Buy Fedora Core 3 Linux CD's in India. Fedora Core 3 Linux Now Available Fedora Core 3 CD's We are providing the free downloadable version of Fedora Core 3 Linux CDs, which is distributed under GNU public
 
Jdbc batch insert
as argument. Once your driver is loaded you connect your front end java application... Jdbc batch insert Jdbc batch insert  ...; In this Tutorial we want to describe you a code that helps you in understand Jdbc batch
 
Jdbc batch update
a connection between the front-backend of your Java application. 3)DriverManager.get... Jdbc batch update Jdbc batch update  ...;            Jdbc Update
 
Jdbc connection
the name of driver class by passing driver as an argument. 3..., pass); System.out.println("jdbc driver for mysql : "... Jdbc connection Jdbc connection   
 
Java program to get data type of column field
Name of [3] Column data type is =VARCHAR Name of [4] Column data type... Java program to get data type of column field Java program to get data type of column field    
 
Data Type: String
of VelocityContext Class. 3:- Create Template class object, Template  class object... Data Type: String Data Type: String...; This Example shows you how to use string data type in velocity. 
 
JDBC Fetch
JDBC Fetch JDBC Fetch     ... to describe you an example from Jdbc Fetch. The code illustrates a class Jdbc Fetch...)The driver loading follows the next step, by calling a class.forName
 
Data Type: number
of VelocityContext Class. 3:- Create Template class object, Template  class object... Data Type: number Data Type: number...; This Example shows you how to use number data type in velocity
 
JDBC Steps ? Basic steps in writing a JDBC Application
for loading the JDBC driver: Class.forName(driver).newInstance();   ... JDBC Steps,Steps of writing JDBC Applications JDBC Steps – Basic steps in writing a JDBC Application  
 
Nexenta OS Alpha 3 has been released
Nexenta OS Alpha 3 has been released Nexenta OS Alpha 3 has been released This release contains 3,596 packages... the numerous pieces together. At the moment, Nexenta is not part of the [WWW] Debian
 
Features of JDBC 4.0
of JDBC driver class: In JDBC 4 invoking the getConnection() on DriverManager... for RowId data type: JDBC introduces  support for ROWID, a data type... Features of JDBC 4.0 Features of JDBC 4.0  
 
Jdbc Nested Resultset
Jdbc Nested Resultset Jdbc Nested Resultset...; The JDBC Nested Result Set  is the simplest join algorithm... that helps in understanding JDBC Nested Result Set. The code include a class
 
Core Java Interview Question Page 3
Java Interview Question Page 3    ... classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic funcationality of your
 
JDBC - Java Database Connectivity Tutorial
, JDBC Driver Manager, The JDBC Test Suite and JDBC-ODBC Bridge.  ... a uniform interface for accessing various relational databases. JDBC is a core part....      JDBC Driver and Its Types   
 
Java error illegal start of type
Java error illegal start of type Java error illegal start of type        ...;      The Java error illegal start of type
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.