Professional Documents
Culture Documents
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.
JDBC II
Types of JDBC drivers: -------------There are four types of JDBC drivers: --------
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)
Java Application
JDBC program
Driver
DB
library
Client machine
I machine
SQL ENGINE
DB
server
DB
library
II machine
Server machine
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).
JDBC IV
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.
Architecture :------------
JDBC V
Java
Application
JDBC
Prog.
SQL
Engine
Driver
Machine I
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
PreparedStatement
CallableStatement
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) --
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.
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) --
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
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;
(1,a)
(2,b)
(3..)
Call Hello(?,?)
(1,a)
(2,b)
in parameter
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
DBUtil.cleanup(con,cs);
}
}
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
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 :-------
JDBC XIII
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: ------
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
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: ---
Lookup(string)
Bind(string,object)
Unbind(string)
Rebind(string,object)
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
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)
}
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("");
}
}
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
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