You are on page 1of 18

JDBC

java database connectivity


J2EE 1.4:-------- JDBC
Servlet
JSP
RMI
Database interaction in c/c++ prog:------

Java Beans
Java mail
JNDI
EJB

JMS
JTA
JAAS
Mysql

C/C++
prog.
DBI
Library

JDBC I

Use DB library
DB
library
Database interaction in java prog: ------

Mysql

Java
prog.

Driver1

Mysql connection
DB library

Driver2

Oracle

Oracle connection

DB library

When you developing an application in c/c++ interact with the database you need to use database vendor for
library in the program directly. In feature if you want to migrate database then you change lots of codes, because
of using runtime specific library in the program directly. your program and database will become tightly couple.
This increase the direct dependency between program and database and decrease application flexibility then
automatically maintenance will be increased .
To avoid this problem sun has provided portable API called JDBC API which allows you to interact with any
database with less maintenance.
In JDBC API, SUN has provided more interfaces whose implementation is done by database vendor and supply
along database institution.
When java developer is writing a program to interact with the database simply they have to use API provided in
JDBC by ignoring the implementation details done by database vendor .this JDBC API makes your program
portable and flexibility for any database interaction.
In JDBC program you are not going to use vendor specific library directly. These are moved to middle component
called driver. Which sits between your program and database and allows you to interact with the database.
Every driver is a java class which is implemented and provided by database vendor.
When you interact with any database 1st you need to select the driver provided by the vendor. Then driver placed
remaining operations.

ODBC driver provided by Microsoft before to JDBC technology Microsoft has introduce ODBC drivers interact
with the database. If you want to interact ODBC driver for database interaction 1st you need to configure data
source name (DNS).
Steps to configure DSN: ------ Click on start ------- setting control panel --------performance and maintenance-------- Administrative Tools------Data Sources (ODBC)
Click on add button
Select Microsoft ODBC for oracle Driver and click on finish button.
Provide data source name as JLCDSN & username as rajiv / sri and click on ok.
With the ODBC driver there is no maintenance for your application when you migrate the database.
But big problem with the ODBC driver is OS dependent.
ODBC driver will come freely along with window OS will not available with another OS.
ODBC driver is implementing in C language.

Steps to write the JDBC driver program: ------------

JDBC II

Load the driver class.


Establish the connection.
Create the statement
Prepare the query and execute it .query submit to the database engine
Processor result
Close the statements and connection.

Types of JDBC drivers: -------------There are four types of JDBC drivers: --------

Type I : JDBC-ODBC bridge Driver


Type II : partial native-partial java Driver
Type III : net protocol Driver
Type IV : pure java Driver

Type I driver: ----------Name: JDBC:ODBC bridge Driver


Driver class: sun.jdbc.odbc.JdbcOdbcDriver
URL: jdbc:odbc:DataSourceName(DSN)
User name: db user
Password: db password
Software:j2sdk 1.4.2 and db server.
Path: %path%;e:\j2sdk 1.4.2\bin;
Classpath: %classpath%;e:\j2sdk1.4.2\lib;
Vendor: sun

*/ Example using Type I driver */


create table b15student(sid number(5),sname varchar2(20),email varchar2(20),phone number(10));
import java.sql.*;
class jdbcEx1
{
public static void main(String as[])
{
try
{
//step 1 : Load the driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river");
//step 2 : Establish the connection
Connection

//step 3 : create the statement


Statement st=con.createStatement();
//step 4 : prepare and execute the
SQL statement
String sql="insert into student1
values('44','DDD','D@sd.com')";
int x=st.executeUpdate(sql);
//step 5 : process the Results
if(x==1)
{
System.out.println("inserted");
}

System.out.println("Not
inserted");
}
//step 6 : close all
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}

con=DriverManager.getConnection("jdbc:o
dbc:bajji","scott","tiger");

else
{

}
}

Advantage :----------JDBC
Type I is very easy to use and maintain.
Type I is suitable for migration applications without changing the data source name(DSN).
No extra software is required for the type I implementation.
Performance of the Type I is acceptable .

III

Disadvantage :--------- Type I driver implementation is possible in window OS only because ODBC drivers available only with
windows.
Performance of this driver is not excellent but acceptable
Architecture of Type I Driver:-----JDBC
Program

JDBC
Driver

ODBC
Driver

DB
(database)

Type II Driver :------Name: partial native partial java Driver


Driver class: oracle.jdbc.driver.OracleDriver
URL: jdbc:oracle:oci8:@ host name:port number:service name
Example :--- jdbc:oracle:oci8@localhost:1521:javasree
Here 1521 port number
javasree
global name
User name: db user
Password: db password
Software: oracle client-server Edition .
Path: %path%;e:\oracle\ora90\bin;
Classpath: %classpath%;e:\oracle\ora90\jdbc\lib\classes 111.jar ;
Vendor: db vendor
Architecture Type II Driver :--------

Java Application

JDBC program

Driver

DB
library
Client machine

I machine

SQL ENGINE

DB
server

DB
library
II machine

Server machine

Advantage :------------- Type II is faster than all other drivers.


Type II is very good in platform but in 2nd place .type II is number 1 in speed.

Disadvantage :------ In Type II both client and server machine both will have the library when database is migrated then you
will get much maintenance because you need to re-install client library in all the client machines(this is
very big problem).

Type III Driver :-------

JDBC IV

Name: net protocol Driver/java net Driver


Driver class: ids.driver.ids Driver
URL: jdbc:ids:\\localhost\12\conn
User name: db user
Password: db password
Software: install IDS server .
Path: %path%;e:\idsserver\idss.exe;
Classpath: %classpath%;e:\idsserver\.....\idsdrv.jar
Vendor: intersolv
Architecture :-----Machine II
Java
Application
JDBC
program

Driver

Machine I

IDS Server

DB sever

DB
library

DB library

middleware server

machine III

Advantage : --- In Type III DB libraries belongs to client or moved to middle ware server called ids server because of
this lots of maintenance will be reduce.
Type III is suitable for internet based application.
Disadvantage :-------- You need to purchase extra software of ids server.
Because of having middle ware server between your program and database server, performance and
speed will be come down.

Type IV Driver:------Name: java Driver


Vendor: db vendor
For oracle :-------

Driver class: oracle.jdbc.driver.OracleDriver


URL: jdbc:oracle:thin:@rajiv:1521:javasree","scott","tiger
User name: db user /sri/ scott
Password: db password /sri/ tiger
Software: oracle enterprise version /edition
Driver
class: com.mysql.jdbc.Driver
Path: %path%;E:\oracle\ora90\BIN;
URL:
jdbc:mysql://host_name/dataBaseName
Classpath : %classpath%;E:\oracle\ora90\jdbc\lib\classes 111.jar;
Example :--- jdbc:mysql://localhost/b15db
User name: root
Password: jlc/rajiv
Software: mysql software.
Path: NA
(not required)
Classpath : %classpath%;E:\b15\jdbc\mysql.jar;

For mysql :-----

Architecture :------------

JDBC V

Java
Application
JDBC
Prog.

SQL
Engine
Driver

Machine I

Server side DB library

machine II

import java.sql.*;
class jdbcEx2
{
public static void main(String as[])
{
try
{
//step 1
Class.forName("oracle.jdbc.driver.OracleDriver");
//step 2
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@rajiv:1521:javasree","scott","tiger");
//step 3
Statement st=con.createStatement();
//step 4
String sql="select *from student";
ResultSet rs=st.executeQuery(sql);
//step 5
String id=null;
String sn=null;
String em=null;
while(rs.next())
{
id=rs.getString(1);
sn=rs.getString(2);
em=rs.getString(3);
System.out.println(""+id+"\t"+sn+"\t"+em);
}
//step 6
rs.close();
st.close();
con.close();
}

catch(Exception e)
{
System.out.println(e);
}
}
}

JDBC VI

Types of JDBC statements: -------


Statement

PreparedStatement

CallableStatement

Statement :------- following is the way to create the statement

Statement st=con.create Statement();


Statement st=con.create Statement(A,B);
Statement st=con.create Statement(A,B,C);

After getting the statement object you can invokes one of the following three methods to execute the sql
statement :-----boolean execute(sql) -- insert,update,delete
all are string parameter
int executeUpdate(sql) --

ResultSet executeQuery(sql) ------- select


When you use execute() method it return either True/False based on whether operation is completed successfully
or not.
When you use executeUpdate() it return a number which is showing the number of records affected(no of record
inserted,updated,deleted)
When you use executeQuery() method it will always for the select statement .which return the ResultSet object
which is capable of storing multiple records return from the database.
When you send the sql statement to the sql engine ,it will be compiling and executed every time.
JDBC Program
Int x=st.executeUpdate(sql)
-------------------------

5 sec
5 sec

SQL Engine
---------------------------

Compile

5sec

Execute

5 sec

Total time for 1 query execution = request time+ processing time +response time = 5+10+5= 20 sec.
With one statement object you can execute multiple sql statements.

PreparedStatement :-------- PreparedStatement interface is extending Statement interface.


Following is the way to create the PreparedStatement object :------- PreparedStatement ps=con. PreparedStatement (String);
PreparedStatement ps=con. PreparedStatement (String,A,B);
PreparedStatement ps=con. PreparedStatement (String,A,B,C);

sql statement

Once PreparedStatement object is created you can execute the sql statement using one of the following
methods:----boolean execute(sql) -- insert,update,delete
all are string parameter
int executeUpdate(sql) --

ResultSet executeQuery(sql) ------- select


With one PreparedStatement object you can execute only one sql statement .you cant execute multiple sql
statements like statement .

When you send the sql statement to the sql engine using PreparedStatement then query will be compile only one
time(1st time )and will be executed every time directly.

Above figure
1st time query execution = request time+ processing time +response time = 5+10+5= 20 sec.
Remaining 99th time =5+5+5=15 (here save the time of compilation(5 sec))

CallableStatement :------------

JDBC VII

CallableStatement interface extends PreparedStatement interface.


CallableStatement are mainly used to execute stored procedures.
Following is the way to create CallableStatement object:------- CallableStatement cs=con. Prepare.Call (String);
CallableStatement cs=con. Prepare .Call(String,A,B);
CallableStatement cs=con. Prepare.Call (String,A,B,C);
here String is not sql statement it is call to Stored_procedure like { call p1() }.

Stored procedure
Stored procedure which will be compiling and stored in database memory.
When invoked the stored procedure it will executed directly without compilation so Compilation time will be
saved.
It will contain multiple PL/SQL statements including simple statement, conditional checks and looping
statements etc.
With one stored procedure you can do multiple sql operation .
Create or replace procedure procedure_name
(var[in/out/inout]datatype,.....)
as
declare
var datatype
---------begine
------------------end;
Stored procedure is PL/SQL block with some name, stored procedure takes parameter and doesn't
return any value
create or replace procedure b14p1(sid number)
as
declare
m1 number(3);
m2 number(3);
m3 number(3);
a number(7,2);
status char(10);
begine
select m1,m2,m3 into m1,m2,m3 from b14 student99 where sid=1;
a:=(m1+m2+m3)/3;
if a=25 then
status:='excellent';
else if a>20 then

status:='good';
else
status:='average';
end if;
update b14 student99 set average=a,
status='exellent where sid=1;
end;
write a stored procedure with the name Hello which has to take three number as parameters and has to finf the
sum of three numbers and has to display the result.
create or replace Hello(a number, b number, c number)
JDBC VIII
as
declare
s number;
begine
s:a+b+c;
dbms_output.putline(s);
end;
call Hello(10,20,30);
assume there is a table called student with the following columns
sid
sname
email
phone
feepaid
feebal
there is one more backup table called table_backup which also have same columns with one extra column called
od (operation date)
write a stored procedure which has to move the record from main table to backup table whenever updating and
deletion operations are having in the main table .
create or replace moveToBackup(id number)
as
declare
sn char(10);
em char(10);
ph char(10);
fp number;
fb number;
od date;
begin
select sname,email,phone,feepaid,feebal into sn,em,ph,fp,fb from student_table where
sid=id;
od:=sysdate;
insert into student_table_backup values(id,snem,ph,fp,fb,od);
end;

ADVANTAGE of stored procedure: ---------Stored procedure is data centric i.e. entire logical implementation are doing inside the database only.
Reduce traffic b/w network (ii) increase performance (iii) save times
Reduce the n/w traffic since request containing multiple queries will be send once.
Increase the performance because stored procedure will compile once and directly executed when you call it.

When you create the stored procedure immediately it will compile and it will stored into database memory later
new or call the stored procedure. Then it will execute directly. Thus compilation time will be reduce.
stored procedure contain multiple SQL statement so that one call procedure execute multiple
SQL statement which is stored into SQL. This reduces the network traffic between your application and database
server. so that performance of the application will be increase.

Types of parameter: ----- stored procedure takes the parameter which is useful to send the data
from client to database server and from database server to client.
There are three types of parameter: -----JDBC IX
(i) in parameter (ii) out parameter (iii)inout parameter
If you using CallableStatement by making a single call to stored procedureyou can execute multiple Sql
operation and we can reduce the network traffic.
Using CallableStatement you can invoke the stored procedure.
When you invoking the stored procedure you need to pass the parameters ,you can have three types of
parameters:------(i) in parameter (ii) out parameter (iii)inout parameter
/*Example with CallableStatement
create or replace procedure findSum(a in number, b in number, s out number)
as
begin
s:=a+b;
end;
*/
/*
create or replace procedure p2(a number,b in number,s out number)
as
begin
s:=a+b;
// insert into abs values(a,b,s);
end;
*/
package com.javasree.jdbc;
import java.sql.*;
import com.javasree.util.*;
public class JdbcEx6
{
Int a=10;
public static void main(String as[])
Int
b=20;
{
{
Connection con=null;
Call Hello(?,?);}
CallableStatement cs=null;

Example with CallableStatement

//variable to store in database


int a=Integer.parseInt(as[0]);
int b=Integer.parseInt(as[1]);
try
{
con=DBUtil.getOracleConnection();
cs=con.prepareCall("{call p2(?,?,?)}");
cs.setInt(1,a);
cs.setInt(2,b);
cs.registerOutParameter(3,4);
int x=cs.executeUpdate();
int s=cs.getInt(3);
System.out.println("Sum is:"+s);

(1,a)
(2,b)
(3..)
Call Hello(?,?)
(1,a)
(2,b)

in parameter

Hello(a in number,b in number)


-----------------out
parameter

Hello(a in number,b in number,s


out number )
--------Hello(a in number,b inout
number)
b:=a+b;
---------Inout parameter

}
catch(Exception e)
{
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,cs);
}
}

/*Example using PreparedStatement ,ResultSet with Type IV driver in mysql */


package com.javashree.jdbc;
import com.javashree.util.*;
import java.sql.*;
import java.util.*;
public class FeeManager
{
public int addFeeInfo(int sid,String
sname,double totalfee,double feepaid)
{
Connection con=null;
Statement st=null;
int x=0;
try
{
con=DButil.getOracleConnection();
st=con.createStatement();
String sql="insert into fee
values("+sid+",'"+sname+"',"+totalfee+",
"+feepaid+")";
x=st.executeUpdate(sql);
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
DButil.cleanup(st,con);
}
return x;
}
public int updateFeeInfo(int sid,double
feepaid)
{
Connection con=null;
Statement st=null;
int x=0;
try
{
con=DButil.getOracleConnection();
st=con.createStatement();
double fp=getFeePaidBySid(sid);
double fp1=feepaid+fp;

finally
{
DButil.cleanup(st,con);
}
return x;
}
public ArrayList getFeeInfoBySid(int
sid)
{
Connection con=null;
Statement st=null;
ArrayList al=new ArrayList();
try
{
con=DButil.getOracleConnection();
st=con.createStatement();
String sql="select *from fee where
sid="+sid;
ResultSet rs=st.executeQuery(sql);
if(rs.next())
{
int id=rs.getInt(1);
String sname=rs.getString(2);
double tf=rs.getDouble(3);
double fp=rs.getDouble(4);
al.add(new Integer(id));
al.add(sname);
al.add(new Double(tf));
al.add(new Double(fp));
}
rs.close();
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
DButil.cleanup(st,con);
}
return al;
}

Connection con=null;
Statement st=null;
double feepaid=0.0;
try
{
con=DButil.getOracleCon
nection();
st=con.createStatement();
String sql="select feepaid
from fee where sid="+sid;
ResultSet
rs=st.executeQuery(sql);
if(rs.next())
{
feepaid=rs.getDouble(1);
}
rs.close();
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
DButil.cleanup(st,con);
}
return feepaid;
}
}

Create table
Create table
b15student(sid int primary
key,sname
varchar2(20),email
varchar2(20),phone long);

JDBC X

String sql="update fee set


feepaid="+fp1+" where sid="+sid;
x=st.executeUpdate(sql);
}catch(Exception e)
{
e.printStackTrace();
}

public double getFeePaidBySid(int sid)


{

TYPE IV
PreparedStatement

Database metadata

JDBC XI

This interface provide the functionality to get the information about database ,Driver and also it provides the
functionality to check whether database is supporting particular feature or not.
ResultSet metadata :------------This interface provides the functionality to get the information about ResultSet . the information whenever you
can get on this interface is,number of column available ,table name.column_name,column_type etc.
String sql=select sid,sname,feebal from student s,fee f
Where s.sid=f.sid;
rs =st.executeQuery(sql);
rs.getcolumnCount();
--------- count number of columns.
Creating the resultSet MetaData object :-------ResultSet MetaData rsmd=rs.getMetaData();
package com.javasree.jdbc;
System.out.println(dbmd.getDefaultTransactionIsola
tion());
import java.sql.*;
import com.javasree.util.*;
System.out.println(dbmd.supportsTransactions());
public class JdbcEx7
{
System.out.println(dbmd.supportsBatchUpdates());
public static void main(String as[])
}
{
catch(Exception e)
Connection con=null;
{
PreparedStatement ps=null;
System.out.println(e);
try
}
{
finally
con=DBUtil.getMySqlConnection();
{
DatabaseMetaData dbmd=con.getMetaData();
DBUtil.cleanup(con,ps);
System.out.println(dbmd.getJDBCMajorVersion());
}
System.out.println(dbmd.getJDBCMinorVersion());
}
System.out.println(dbmd.getDatabaseMajorVersion()); }
ResultSet is used to accommodate multiple records fetched from the database table.
We can divide the ResultSet into two types based on scroll ability :----- Forward ResultSet
Scrollable ResultSet
Forward ResultSet:------Statement st=con.create Statement()
rs=st.executeQuery(sql)

----------Forward ResultSet

when ResultSet is created as forward only then you can move the cursor /pointer in the forward direction only.
you cant move in backward or reverse direction.

When ResultSet is forward only then you can call only following method of the ResultSet object.
o next()
o get xxx(int)
o get xxx(String)
Scrollable ResultSet :-------------Statement st=con.create
Statement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery(sql)
---------- scrollable / read only
TYPE_FORWARD_ONLY
TYPE_SCROLL_SENSITIVE
TYPE_SCROLL_INSENSITIVE
Scrollability

Updatability
CONCUR_READ_ONLY
CONCUR_UPDATABLE

Holdebility
HOLD_CURSORES_OVER_COMMIT
HOLD_CURSORES_AT_COMMIT

When ResultSet is scrollable then the movement of the cursor in both forward and backward direction .
When ResultSet is scrollable then you can call the following method on ResultSet object
o next()
o get xxx(int)
o get xxx(String)

boolean relative(int);
boolean absolute(int);
boolean previous();
boolean last();
boolean isLast();
boolean first();

JDBC XII

boolean isFirst();
boolean isBeforeFirst();
boolean isAfterLast();
void afterLast();
void beforeFirst();

you can divide the ResultSet again into two types based on updating ability:------- read only ResultSet
Updatable ResultSet
Read only ResultSet: -------- By default ResultSet is read only.
When ResultSet is read only you can just read the data from object you cant the update the data in ResultSet
object.
Updatable ResultSet: --- To create the ResultSet as updatable then you have to use the statement which is
created as follows: ------Statement st= con.create
Statement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
When ResultSet is updatable then you can do the following operation on the ResultSet :----- Read the data from ResultSet
getXXX(int)
get XXX(String)
you can update data in the ResultSet object
updateXXX(String,XXX)
updateXXX(int,XXX)

updateRow()
you can delete the row from ResultSet:------- void deleteRow()
you can insert the row in the ResultSet:------ void insertRow()
moveToInsertRow()

package com.javasree.jdbc;
import java.sql.*;
import com.javasree.util.*;
public class JdbcEx9
{
public static void main(String as[])
{
Connection con=null;
Statement ps=null;
try
{
con=DBUtil.getMySqlConnection();
ps=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Resul
tSet.CONCUR_READ_ONLY);
ResultSet rs=ps.executeQuery("select * from student2");

rs.relative(2);
rs.relative(-1);
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.isFirst());
System.out.println(rs.isBeforeFirst());
rs.relative(-2);
System.out.println(rs.isLast());
System.out.println(rs.isAfterLast());
System.out.println(rs.isFirst());
System.out.println(rs.isBeforeFirst());
rs.relative(2);
System.out.println(rs.isLast());
System.out.println(rs.isAfterLast());
System.out.println(rs.isFirst());
System.out.println(rs.isBeforeFirst());

System.out.println("2nd Record");
rs.absolute(2);
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));

}
catch(Exception e)
{
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,ps);
}

System.out.println("Reverse Order");
rs.afterLast();
while(rs.previous())
{
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");
}

}
}

Batch update
This concept will be useful to send multiple query once in the database. Example: ------ if you want to execute
100 sql statement then you needs to interact database 100 times .this increases the network traffic in stead of
sending sql statement one by one to the database. If we send as a bulk we can reduce the traffic between your
application and database server. When you are implementing batch updates concepts .you need to use the
following method of statement interface :--- Void addBatch(String)
Int [] executeBatch()
Void clearBatch()
Connection pooling :-------

Installing Weblogic application server :-------

Click on the installer called platform 811 win-32.exe.


Click on next
Click Yes and click next.
Provide E:/bea as bea home directory and click on next.
Select complete installation type and click on next.
Provide E:/bea/weblogic 81 as product installation directory and click on next.
Uncheck the 2 checked boxes and click on done.

JDBC XIII

Creating your own Weblogic domain: ---------

Click on Start ------ program-----bea Weblogic platform 8.1----configuration wizard.


Select create a new Weblogic configuration and click on next.
JDBC XIV
Select basic Weblogic server domain and click on next.
Select express and click on next
Provide username and password and confirm password and click on next(Weblogic as user name rajiv as
password)
Select the development mode and select bea supplied sdk and click on next.
Provide configuration name as javasree(you can provide your own name) and click on create.
Click on done.
Run the setEnv.bat
Location: ---- E:\>cd bea\user-projects\domains\javasree>setEnv [Enter]

Starting Weblogic server: -- Click on start-------program------bea Weblogic platform 8.1---user-project 8javasree---start server.
Open the Weblogic console: ------ Open the brawser and type the following
Username web logic
http://localhost:7001/console
Password rajiv
provide the user name and password and click on sign in button
Configuring connection pools in Weblogic console :------ click on javasree ------services-----jdbc---connection pools
click on configure a new jdbc connection pool.
Select database type as mysql and databse driver as other and click on continue.
Provide name as MYSQLPOOL,driver class as com Mysql.jdbc.Driver.
URL : jdbc:mysql://localhost\b15db (here I am giving rajivsh as db test drive)
User name : root
Password : srinivas
Confirm password and click on test drive configuration.
Click on create and deploy button.
Configuring data sources in Weblogic console: ------

Click on javasree ----sevices----jdbc----data source.


Click on configure a new jdbc data source.
Provide data source name as: -------Jdbc/mysqlpool and click on continue --- here i have given jdbc/MYSQLPOOL
Select mysqlpool from the list and click on continue.
Click on create.

Problem with driver manager connection management : --------- Java naming directory interface -------JNDI ---it is a kind of registry having key and its corresponding
values.
When you are using driver manager to get the connection then you need to provide URL, user
name and password every time and before to this you need to load the driver class. Doing these
things every time is little bit overhead.
When you call close method on the connection which is taken from driver manager then
connection will close permanently. Later when you request for a connection driver manager create
a new connection objects .creating every time a new connection and destroying the connection is
overhead.
Solution: --- To solve these problems you use connection pooling mechanism.

JDBC XV

Required things to use connection pooling mechanism: -------

One server is required (server can be an application server or web sever recommendable server in
production in any application server)
Driver is the way to create the
You need to configure the connection pool.
connection.
You need to configure the data sources
DataSource------------Interface
Following thing will happen when you configure pool in the server: ----- With the given information multiple connection will be created to create one connection driver class URL,
user name, password will be used.
NOTE : ------- initially no. of connection available in the pool will be depending on server
and your requirement.
The pool of connections created will be associated with the pool_name given by you.
NOTE : ---- in our configuration we given the pool_name is MySqlPool.
Following things will happen when you configure data sources in server: ---

d.s.n : -------------- jdbc\oracle pool


JNDI name : ----- jdbc/oracle pool
Pool name : ----- oracle pool

Lookup(string)
Bind(string,object)
Unbind(string)
Rebind(string,object)

DataSource ds1= new MySqlDataSource(MySqlPool);


DataSource ds2= new oracleDataSource(oraclePool);
When you configuring DataSources mainly you are providing JNDI name & pool name.
With the given pool DataSource object will be created for Example : -- DataSource ds1=new MySqlDataSource(MySqlPool);
DataSource ds2= new oracleDataSource(oraclePool);
Server will bind DataSource object in the JNDI registry with the given JNDI name .
Context ctx=new InitialContext();
Ctx.bind(jdbc\MySqlPool,ds1);

DataSource ds=lookup(jdbc\MySqlPool);

Void main()
p.put(factory class,URL)
p.put(PROVIDE URL,+3://localhost:7001);
Context ctx new InitialContext(P); // P------------properties
ds=(DataSource)ctx.lookup(jdbc\MySqlPool);
con=ds.getconnection();
------------------------Con.close();

package com.javasree.util;
/*
DBUtilDS.java 1.0
Author : B13 batch
*/
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;

DataSource
Lookup

public class DBUtilDS


{
static Context ctx=null;
Interface
static
{
context
try
{
Properties p=new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"weblo
gic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL,"t3://localhost:7001");
ctx=new InitialContext(p);
}
catch(Exception e)
{
System.out.println(e);
}
}
package com.javasree.jdbc;
import java.sql.*;
import com.javasree.util.*;
public class JdbcEx12
{

Javax.naming package
Public interface Context
{
Static final String
INITIAL_CONTEXT_FACTORY;
Static final String PROVIDER_URL;
Object lookup(String)
Void bind(String,Object)
Void rebind(String,Object)
Void unbind(String)
namingEnumeration list(String)
}

/* public static Connection getMySqlConnection()


throws Exception
{
Object o=ctx.lookup("jdbc/MySqlPool");
DataSource ds=(DataSource)o;
Connection con=ds.getConnection();
return con;
}*/
public static Connection getOracleConnection()
throws Exception
{
Object o=ctx.lookup("jdbc/OraclePool");
DataSource ds=(DataSource)o;
Connection con=ds.getConnection();
return con;
}
public static void cleanup(Connection con,Statement
st)
{
try
{
if(st!=null)
st.close();
JDBC XVI
if(con!=null)
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
int x[]=ps.executeBatch();
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
ResultSet rs=ps.executeQuery("select * from
student1");

public static void main(String as[])


{
Connection con=null;
Statement ps=null;
try
{
con=DBUtil.getMySqlConnection();
ps=con.createStatement();

while(rs.next())
{
System.out.print(rs.getString(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");
}

ps.addBatch("insert into student1


values('22','22','22','22')");
ps.addBatch("insert into student1
values('33','33','33','33')");
ps.addBatch("update student1 set
sname='11',email='11',phone='11' where sid='1'");
ps.addBatch("delete from student1 where sid='2'");

}
catch(Exception e)
{
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,ps);
} } }

LDAP Server
con
con

con
con

con

ds1

Name

Value

Jdbc/
mysql
pool

ds1

Ctx=new InitialContext() // here no need to provide P


Ctx.bind(jdbc/MySqlPool,ds1);

package com.javasree.jdbc;
rs.absolute(3);
rs.deleteRow();
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");

import java.sql.*;
import com.javasree.util.*;
public class JdbcEx10
{
public static void main(String as[])
{
Connection con=null;
Statement ps=null;
try
{
con=DBUtil.getMySqlConnection();

rs.moveToInsertRow();
rs.updateInt(1,77);
rs.updateString(2,"G");
rs.updateString(3,"77");
rs.insertRow();
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");

ps=con.createStatement(ResultSet.TYPE_SCROLL_SENSITI
VE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=ps.executeQuery("select * from student3");
System.out.println("2nd Record");

rs.absolute(2);
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");
rs.updateString(3,"2222");
rs.updateRow();
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println("");

catch(Exception e)
{
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,ps);
}
}
}

JDBC XVII

JDBC XVI

08-04-2008

You might also like