What is JDBC Driver ?

JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driverinterface in their database driver.

JDBC Drivers Types:

JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below:

Type 1: JDBC-ODBC Bridge Driver:

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API:

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.

If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java:

In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful.

Type 4: 100% pure Java:

In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

Which Driver should be used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.

The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only.

Following table lists down popular JDBC driver names and database URL.

RDBMS

JDBC driver name

URL format

MySQL

com.mysql.jdbc.Driver

jdbc:mysql://hostname/ databaseName

ORACLE

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@hostname:port Number:databaseName

DB2

COM.ibm.db2.jdbc.net.DB2Driver

jdbc:db2:hostname:port Number/databaseName

Sybase

com.sybase.jdbc.SybDriver

jdbc:sybase:Tds:hostname: port Number/databaseName

JDBC Steps of Processing


  1. Create a Connection
    2. Load JDBC Driver
    3. Open database Connection
    4. Create Statement/PreparedStatement for executing query
    5. Create ResultSet
    6. Fetch Data from ResultSet
    7. Close Statement
    8. Close ResultSet
    9. Close Connection



JDBC Connection

1. Create Connection

Connection is session between database and JDBC, before accessing database it is established. This connection helps to send SQL query to database and return back to client with output. Connection is interface java.sql.Connection



<%

Connection conn=null;

%>







2. Load JDBC Driver

JDBC Driver class is load into java virtual machine (JVM). The Class.forName() method is used to load vendor database class into JVM, it has return type of class. It is registering Driver class.

<%

Class.forName("com.mysql.jdbc.Driver").newInstance();

%>



In JDBC 4.0, it is no longer needed to load vendor class manually. JDBC 4.0 automatically loads Driver class and registers it.



3. Open Database connection

After loading and registering Driver class, have to make database connection with method of DriverManager.getConnection(), returns as Connection. JDBC 4.0 version only need DriverManager.getConnection() method, it finds automatically suitable Driver from list for itself. It is in java.sql.Driver package.

<%

Connection conn =DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

%>

e.g for MySql database we can use jdbcURL string.







<%

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root", "");

%>

project is database name, root is database’s user name with empty password.



Create Statement or PreparedStatement

Statement

Statement is object which send SQL query to database. Statement sends each and every time SQL statement to database server for execution. These Statements can be insert, update, delete, create table, select or any. Statement object can be created by connection objects with createStatement(). Statement is in java.sql.Statement

<%

//Connection conn = null;

//conn is Connection object used in createStatement

Statement stm=null;

stm=conn.createStatement();

stm.executeUpdate("insert into tableName values('FieldName1','FieldName2')");

%>

PreparedStatement

Statement is simple SQL statement and takes no parameters, execute and compile every time when request is generated to database server. PreparedStatement is precompiled SQL statement and reside in PreparedStatement object. This PreparedStatement object executes multiple times SQL statement without compiling it again and again. This is kind of caching SQL statement and execute on parameters specification. First time when it executes, it runs slow but after that it runs much faster than simple Statement Object. Sometimes it is called dynamic statement because it takes parameter setter option.
A SQL statement is given inside when PreparedStatement is creating. PreparedStatement is in
java.sql.PreparedStatement

<%

//Connection conn = null;

PreparedStatement pstm=null;

pstm=conn.prepareStatement("select * from TableName where iEmpID=?");


%>

This PreparedStatement has one parameter and need to set this parameter.

<%

//Connection conn = null;

//conn is Connection object used in prepareStatement

ResultSet rs=null;

PreparedStatement pstm=null;


String VariableName="value";


pstm=conn.prepareStatement("select * from TableName where iEmpID=?");

pstm.setString(1,VariableName);

rs=pstm.executeQuery();


%>

CallableStatement

CallableStatement is used to execute Stored Procedure on database server. Stored Procedure is set of SQL statement which is stored at database server. Work on these SP we need CallableStatement object. Stored procedure can be executed with call statement on database, same thing use here also. CallableStatement also can take parameters.

<%

//Connection conn = null;

//conn is Connection object used in preparedCall


CallableStatement cstm=null;

cstm= conn.prepareCall("call StoredProcedure(?,?)");


cstm.setString(1, variable1);

cstm.setInt(2, variable2);

%>



JDBC ResultSet

Create ResultSet

ResultSet is an object which is used to store the result of executed SQL statement. These ResultSet object can contain Rows if database query having number of rows. ResultSet have number of methods to access column and attribute from RDBMS, commonly get methods. Move to next row, ResultSet next() method is used, and cursor will move to next row of database table. This ResultSet object is maintained in cursor, which points to current row of table data. When ResultSet object is created default cursor position is on before first row, if ResultSet next method is called cursor set to first row of table data.
ResultSet are in
java.sql.ResultSet

<%

Statement stm=null;

stm=conn.createStatement();

// conn is Connection object


ResultSet rs=null;

rs=stm.executeQuery("select * from TableName where iEmpID=10");


String sEmpName=null;


while(rs.next())

{

sEmpName=rs.getString("DataBaseAttributeName");

}

%>

It is possible scrollable ResultSet, scrollable ResultSet help us to revisit again at previous cursor point.
Result with simple Statement

<%

Statement stm=null;

stm=conn.createStatement();

// conn is Connection object


ResultSet rs=null;

rs=stm.executeQuery("select * from TableName where iEmpID=10");


String sEmpName=null;


rs.beforeFirst();


while(rs.next())

{

sEmpName=rs.getString("DataBaseAttributeName");

}

%>

ResultSet with PreparedStatement

<%

// conn is Connection object

PreparedStatement pstm=null;

pstm=conn.prepareStatement("select * from TableName where iEmpID=?");

pstm.setString(1,VariableName);

ResultSet rs=null;

rs=pstm.executeQuery();

String sEmpName=null;

while(rs.next())

{

sEmpName=rs.getString("DataBaseAttributeName");

}

%>

Other scrollable ResultSet are

rs.afterLast();

Fetching data from ResultSet

Fetching data from ResultSet is easy task; it provides lot of methods to get any type of data. With iterator we can fetch all rows from table one by one next method of ResultSet.



JDBC Close Connection Object

Close Statement

After completion use of Statement object in java, it should clear from java objects for Garbage collection. Garbage collection automatically free space from memory, give chance to other objects and resources to occupy space in memory. This Statement can be closed by close method of Statement, should be in try catch block. Close Statement help to boost performance of application.

<%

try{

if(stm!=null){

stm.close();

}

}

catch(Exception e)

{

e.printStackTrace();

}

%>

Close ResultSet

After using ResultSet, ResultSet object in no longer needed, it should be removed from memory. This can be done by close method of ResultSet. Close help to boost performance of application.

<%

try{

if(rs!=null){

rs.close();

}

}

catch(Exception e)

{

e.printStackTrace();

}

%>

Close Connection

Every Connection makes an individual session with database. This session reserves particular resources for itself. Every database have default connection pool, Mysql max_connections are 100. Beyond this limit it throws error of “error too many connection in mysql”. Better it to close connection after it use, get better performance. It is good practice to close each and every connection object after it use.

<%

try{

if(conn!=null){

conn.close();

}

}

catch(Exception e)

{

e.printStackTrace();

}

%>

Or close all objects simultaneously

<%

Connection conn = null;

Statement stm = null;

ResultSet rs = null;

try{

conn=/// get connection from connection object

stm=conn.createStatement();

rs=stm.executeQuery("Select * from tableName");

}

catch(SQLException ex)

{

ex.printStackTrace();

}

try{

if(stm!=null){

stm.close();

}

if(rs!=null){

rs.close();

}

if(conn!=null){

conn.close();

}

}

catch(Exception e)

{

e.printStackTrace();

}

%>

JSP - Database Access

Create Table

To create the Employees table in EMP database, use the following steps:

Step 1:

Open a Command Prompt and change to the installation directory as follows:

C:\>

C:\>cd Program Files\MySQL\bin

C:\Program Files\MySQL\bin>

Step 2:

Login to database as follows

C:\Program Files\MySQL\bin>mysql -u root -p

Enter password: ********

mysql>

Step 3:

Create the table Employee in TEST database as follows:

mysql> use TEST;

mysql> create table Employees

(

id int not null,

age int not null,

first varchar (255),

last varchar (255)

);

Query OK, 0 rows affected (0.08 sec)

mysql>



Create Data Records

Finally you create few records in Employee table as follows:

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');

Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');

Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');

Query OK, 1 row affected (0.00 sec)

mysql>





Mysqljsp.jsp

<%@page import="java.sql.*"%>

<%

response.setHeader("Pragma","no-cache");

response.setHeader("Cache-Control","no-cache");

response.setDateHeader("Expires",-1);

try

{

String query=request.getParameter("sql");

if(query!=null)

{

new com.mysql.jdbc.Driver();

String url="jdbc:mysql://localhost:3306/michaeljsp";

Connection con=DriverManager.getConnection(url,"root","root");

Statement stmt=con.createStatement();

if(stmt.execute(query)==false)

{

out.println(stmt.getUpdateCount()+"rows affected");

}

else

{

ResultSet rs=stmt.getResultSet();

ResultSetMetaData md=rs.getMetaData();

out.println("<table border=\"1\"><tr>");

for(int i=1;i<=md.getColumnCount();i++)

{

out.print("<th>"+md.getColumnName(i)+"</th>");

}

out.println("</tr>");

while(rs.next())

{

out.println("<tr>");

for(int i=1;i<=md.getColumnCount();i++)

{

out.print("<td>"+rs.getString(i)+"</td>");

}

out.println("</tr>");

}

out.println("</table>");

rs.close();

}

stmt.close();

con.close();

}

}

catch(Exception e)

{

out.println(e);

}

%>

<form name="sqlForm" methods="post">

SQL statement:<br><input type="text" name="sql" size="50"><br/>

<input type="reset"><input type="submit" value="Execute">

</form>