Connection Polling Transactions Result Set Types

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

ResultSetTypes:

In jdbc applications ResultSets could be classified in the following two ways.

On the basis of ResultSet Concurancy:-

There are 2 types of ResultSets.

1) Read only ResultSet

2) Updatable ResultSet

Read only ResultSet:-

It is a ResultSet, which will allow the users to read the data only.

To refer this ResultSet, we will use the following constant from ResultSet interface.

public static final int CONCUR_READ_ONLY;

2) Updatable ResultSet:-

It is a ResultSet object, which will allow users to perform some updations on its

content. To refer this ResultSet we will use the following constant from ResultSet

interface.

public static final int CONCUR_UPDATABLE;

2)On the basis of the ResultSet cursor movement:-

There are 2 types of ResultSets.

1)Forward only ResultSet

2)Scrollable ResultSet

Forward only ResultSet:-

It is a ResultSet object, which will allow the users to iterate the data in

forward direction. To refer this ResultSet object we will

use the following constant from ResultSet interface.

public static final int TYPE_FORWARD_ONLY;


Scrollable ResultSet:-

These are the ResultSet objects, which will allow the users to iterate the data in
both forward and backward directions.

There are 2 types of Scrollable ResultSets.

Scroll sensitive ResultSets

Scroll in-sensitive ResultSets

What is the difference between ScrollSensitive ResultSet and ScrollInsensitive


ResultSets?

Scroll sensitive ResultSet is a ResultSet object, which will allow the later

updations from database automatically after creating it. To refer this ResultSet we
will use the following constant.

public static final int TYPE_SCROLL_SENSITIVE;

Scroll insensitive ResultSet is a ResultSet object, which will not allow later
updations from database after creating it. To refer this ResultSet we will use

the following constant from ResultSet interface.

public static final int TYPE_SCROLL_INSENSITIVE;

What is the default ResultSet type in JDBC application and How it is possible to
create a specific type of ResultSet object?

The default ResultSet type in the jdbc applications is Read only and forward only.

In jdbc applications we are able to specify the following types of the ResultSet
combination to any particular ResultSet.

read-only, forward only

read-only, scroll sensitive

read-only, scroll insensitive

updatable, forward only

updatable, scroll sensitive

updatable, scroll insensitive


if we want to specity a particular type to the ResultSet object then we should

use either of the above constants combination as a parameter to createStatement()


method, for this we will use the following method.

public Statement createStatement

(int forward / ScrollSensitive / ScrollInsensitive, int readonly / updatable)

Eg: Statement st = con.createSatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_UPDATABLE);

ResultSet rs = con.executeQuery(.);

23:How to iterate the data from Scrollable ResultSet objuect in both forward and
backword direction?

to iterate the data in forward direction from a ResultSet object we will use the
following 2 methods.

public boolean next()

public xxx getXxx(int fieldno.)

Where xxx may be byte, short, char, int, long, float, double.

To iterate the data in backward direction from

Scrollable ResultSet object we will use the following 2 methods.

public boolean previous()

public xxx getXxx(int fieldno)

Where previous() is a Boolean method, which can be used to check


whether the previous record is available or not, if it is available then cursor will be
moved to previous record position.

note:-

refreshRow() is a method from


Scrollable ResultSet object, which can be

used to refresh the current row in the

ResultSet object to allow the later

updations from database. Prototype of

this method is

public void refreshRow()

to move the ResultCursor to before first Record

we should use the following method.

public void beforeFirst();

to move ResultSetcursor after the last record

we will use the following method.

public void afterLast();

to move ResultSet cursor to the first record and

last Record. we should use the following methods.

public void first();

public void last();

to move ResultSet cursor to a particular record

position we should use the following

public void absolute(int recpos);


how to generate ScrollSensitive Result Set and how to reflect the later updations

from database automatically to the ResultSet object?

import java.sql.*;

public class Test{

Public static void main(String[] args)throws Exception

Class.forName(driver className);

Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:XE,system,man
ager);

Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UP
DATABLE);

ResultSet rs = st.executeQuery(select * from employee);

rs.next();

System.out.println(old salary employee.+rs.getFloat(3));

System.in.read();//application is in pause, perform database updations

Rs.refreshRow();

System.out.println(new salary of emp..+rs.getFloat(3));

Where refreshRow() is a method from

Scrollable ResultSet object, which can be

used to refresh the current row in the

ResultSet object to allow the later

updations from database. Prototype of

this method is

public void refreshRow()


Q: How to insert records into Database throws Updatable ResultSet?

If we want to insert a new record on to the database through Updatable ResultSet


object, we will use the following steps.

Step1: Get the Updatable ResultSet object

with fetched data.

Step2: Move ResultSet cursor to the end

of the ResultSet object, where we need to

take a buffer to hold new records data

temporarily, for this we use the following

method from updatable ResultSet object.

public void moveToInsertRow()

Step3: Insert new records data on to the buffer temporarily at Updatable


ResultSet object for this we will use the following method format.

public void updateXxx(int fieldno,xxx value)

Where xxx may be byte, short, int, char, double, float, long.

Step4: Make the temporary insertion as the permanent insertion in Updatable


ResultSet object as will as in database, for this we will use the following method.

public void insertRow()

The following example demonstrates how to insert no. of records onto the database
through Updatable ResultSet objects.

import java.sql.*;

import java.io.*;

public class UpdateResultSetExample{

public static void main(String[] args)throws Exception {

Class.forName(driverClass);

Connection con = DriverManager.getConnection(url,system,manager);


Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UP
DATABLE);

ResultSet rs = st.executeQuery(select * from employee);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

rs.moveToInsertRow();

while(true)

System.out.println(enter employee number);

int eno = Integer.parseInt(br.readLine());

System.out.println(enter employee name);

String ename = br.readLine();

System.out.println(enter employee salary);

float esal = Float.parseFloat(br.readLine());

System.out.println(enter employee address);

String eaddr = br.readLine();

rs.updateInt(1,eno);

rs.updateString(2,ename);

rs.updateFloat(3,esal);

rs.updateString(4,eaddr);

rs.insertRow();

System.out.println(record successfully inserted);

System.out.println(one more record[y/n]);

String option = br.readLine();

if(option.equals(n))

break;

}
}

Q: How to perform updations on Database throws Updatable ResultSet?

By using Updatable ResulSet object we are able to perform some updations on to


the database. To perform updations on to the database through Updatable
ResultSet object we will use the following steps.

Step1: Get the Updatable ResultSet objectd with the fetched data.

Step2: Move ResultSet cursor to a record where we want to perform updations, for
this we will use the following method.

public void absolute(int recordno.)

Step3: Perform Temporary updations on to the particular record, for this we will
use following method.

public void updateXxx(int fieldno,xxx value)

Step4: Make the temporary updation as a parmenent updation on to the Updatable


ResultSet object as well as to the database. For this we will use the following
method.

public void updateRow()

The following example demonstrates how to perform updations on to the database


through Updatable ResultSet object.

import java.sql.*;

public class UpdateResultSetExample{

public static void main(String[] args)throws Exception{

Class.forName(driverclassName);

Connection con = DriverManager.getConnection(url,system,manager);

Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UP
DATABLE);

ResultSet rs = st.executeQuery(select * from employee);

rs.absolute(3);

float newsal = rs.getFloat(3)+500;

rs.updateFloat(3,newsal);
rs.updateRow();

Connection Pooling:-
In jdbc as a java programmer if we want to obtain a connection with a database
then we have the following two approaches.

1) by using DriverManager class of java.sql

2) by using DataSource interface of javax.sql

Sunmicrosystems given DataSource interface , in order to OverCome the problems


of DriverManager Class.

-->DriverManager class always opens a new Physical connection with

the Database.The Connection created by the DriverManager is a non-reusable.

It is used DriverManager class,we must close the Database Connection.Otherwise


the Connection will not be closed until the Database server is shutdown.

DriverManager is increased the burden of the databaseserver because everytime


opening a new Connection and closing a connection need a Heavy work in the
Database server.

To Overcome the above problems of DriverManager , we got DataSource.

With Connection pooing,we have the following two Advantages

1)A connection pool contians a set of Readymade Connections(Already open


Connections).So an Application as no need to wait until the Connection is
opened.The Application gets Connection faster.

2) A Connection in a Connection pool's are Reusable. because once an application


as completed the work then the Connection goes back to the pool.

And Same Connection will be reused for next time.


DataSource will act as a meditator between a java application and a Connection
pool.

DataSource will creates the logical connection to java application whenever the
application closes the logical connection .DataSource will send that connection back
to pool.

The Following Diagram Shows Limitations of DriverManager class getConnection()


method:-

Problems with DriverManager.getConnection() approach:

1. Every time getting the physical connection from the data base takes more time
and resources because of the above drawback application performance is
reduced.
2. Data base server provider for web-application will charge more why because
each new connection request is costly.
3. Even multithreaded environment is also not suggested, we find the problems
such as scalability, consistency... etc.

To solve the above problems we must use connection pooling.

What is connection pool?

ans: connection pool is a group of logical data base connections associated with a
physical data base connection.
What is connection pooling?

ans: Maintaining pool of logical connections is called as connection pooling.

In connection pooling whenever application is started (i.e. project running


started) then connection pool provider first establishes physical connection to the
data base and creates n number of logical connections. (n is fixed value)

Whenever a component in the application (project) requires the connection then


connection pool provider will give the logical connection.

The component of the application (project) uses this logical connection after using
the logical connection component gives that logical connection back to the provider
by calling close method call.
Connection pooling implementations:

1) We can use connection pooling mechanism implemented by (or provided by)


JDBC driver providers.
2) We can use connection pooling mechanism provided by web servers or
application servers.

In real time (or in industry) for web applications (or for web sites) server provided
connection pooling mechanism is used.

The Connection pool implementation can be used in 2-tier or 3-tier architecture.

Important interfaces in javax.sql package:

javax.sql.DataSource
javax.sql.ConnectionPoolDataSource
javax.sql.PooledConnection

JDBC driver provider defines a class that implements javax.sql.DataSource.


JDBC driver provider defines a class that implements
javax.sql.ConnectionPoolDataSource.

JDBC driver provider defines a class that implements javax.sql.PooledConnection.

More about Javax.sql.DataSource

There are three types of implementations of DataSource interface:

1. Basic implementation

Produces a standard Connection object (physical Connection)

Basic implementation is provided by JDBC driver provider.

Means JDBC driver provider defines a class that implements javax.sql.DataSource


to get normal Physical Connection.

This normal physical connection does not provides logical connections.

2. Connection pooling implementation

Produces a Connection object that will automatically participate in connection


pooling.

This implementation works with a middle-tier connection pooling manager.

ie with web server and application server connection pooling manager.

More clearly web server and application server providers will define a class that
implements javax.sql.DataSource by using this class object we cannot get physical
connection we can get logical connection that is already connected to a physical
data base connection.

1st we will discuss basic implementation of DataSource:

This is used to getting physical data base connection and this is similar to
DriverManager

Getting data base connection by using a class that implements DataSource is


simple and more flexible way than DriverManager.

Oracle type4 driver provider defines a class


oracle.jdbc.pool.OracleDataSource implements DataSource by using this
class object we can get oracle data base connection as shown below:

oracle.jdbc.pool.OracleDataSource ds;
ds = new oracle.jdbc.pool.OracleDataSource();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
ds.setURL(url);
Connection con= ds.getConnection("system", "sathish");

javax.sql.PooledConnection interfaces:

PooledConnection interface:

JDBC driver provider defines a class that implements PooledConnection interface

The PooledConnection interface implemented class object contains a physical


connection and this physical connection is connected to logical connections.

By using this object we can get logical connections.

The PooledConnection interface important methods are:


void close()
Closes the physical connection that this PooledConnection object contains.
Connection getConnection()
Creates and returns a logical Connection object that is connected to the
physical connection.

ConnectionPoolDataSource:

JDBC driver provider defines a class that implements ConnectionPoolDataSource to


give PooledConnection implemented class object.

ConnectionPoolDataSource contains two methods:


PooledConnection getPooledConnection()
Attempts to establish a physical database connection that can be used as a
pooled connection.

PooledConnection getPooledConnection(String user, String password)


Attempts to establish a physical database connection that can be used as a
pooled connection.

Oracle implementation of ConnectionPoolDataSource and


PooledConnection
Oracle type4 driver provider defines a classOracleConnectionPoolDataSource
implements ConnectionPoolDataSource and defines another class
OraclePooledConnection implements PooledConnection interface.

These classes are defined in the package oracle.jdbc.pool

OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();


ds.setURL("jdbc:oracle:thin:@localhost:1521:XE");
ds.setUser("system");
ds.setPassword("sathish");
PooledConnection pc = ds.getPooledConnection();//returns PooledConnection
containing logical connections connected to a physical connection.
Connection con = pc.getConnection(); //gives logical connection from a pool
con.close();//returns the logical connection back to pool.
pc.close();//closes the physical connection

import javax.sql.*;
import java.sql.*;
import oracle.jdbc.pool.*;

public class ConnectionPoolDemo{


public static void main(String []args)throws Exception{
OracleConnectionPoolDataSource ocp = new OracleConnectionPoolDataSource();
ocp.setURL("jdbc:oracle:thin:@localhost:1521:XE");
ocp.setUser("system");
ocp.setPassword("sathish);

PooledConnection pc = ocp.getPooledConnection();//gives physical connection

Connection con1 = pc.getConnection();//gives logical connection


Connection con2 = pc.getConnection();//gives logical connection
Connection con3 = pc.getConnection();//gives logical connection

/*con1,con2,con3 are the references to logical connections */


if(con1!=null){
System.out.println("logically connected to oralce");
con1.close();//closes the logical connection
}
if(con2!=null){
System.out.println("logically connected to oralce");
con2.close();//closes the logical connection
}
if(con3!=null){
System.out.println("logically connected to oralce");
con3.close();//closes the logical connection
}//end of last if
}//end of the main
}//end of the class

DataSource :
DataSource will act as a meditator between a java application and a
Connection pool.

DataSource will creates the logical connection to java application whenever


the application closes the logical connection.DataSource will send that
connection back to pool.

DataSource is an interface present in javax.sql package . For DataSource


interface different thrird party vendors are Provided the implementations

Generally we are using Server vendor provided implementations in the


realtime projects
Datasource Object is registred with Naming Service(JNDI) in the server.

The Application Developer will get the DataSource object from JNDI Registry.

To get the DataSource object the Programmer will use InitialContext object
lookup(-) method

The InitialContext class is present in javax.naming package .

First Create DataSource Object in Server


and Register with JNDI
If we are working with Tomcat Server

Open the C:\apache-tomcat-7.0.54\conf\context.xml file add the


following Resource configuration as follows.

Webapp example to do Oracle connections pooling, MySQL connections


pooling, DB2 connections pooling with tomcat7 webserver with steps:

step1: add the following tag inside c:\tomcat7\conf\context.xml

in between <context></context>

for oracle data base:


<Resource
name="jdbc/ods"
type="javax.sql.DataSource"
username="system"
maxWait="5000" driverClassName="oracle.jdbc.driver.OracleDriver"
password="sathish"
url="jdbc:oracle:thin:@localhost:1521:XE"/>

for mysql database:

<Resource name="jdbc/mysqlds" auth="Container"


type="javax.sql.DataSource"
maxWait="10000"
username="root"
password="sathish"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test" />

for db2 data base:

<Resource name="jdbc/db2ds" auth="Container"


type="javax.sql.DataSource"
username="db2admin"
password="sathish"
driverClassName="com.ibm.db2.jcc.DB2Driver"
url="jdbc:db2://localhost:50505/SAMPLE" />

Step2:

Example code In Jdbc Program To get DataSource object from


JNDI :-

InitialContext ic=new InitialContext();

DataSource dataSource=ic.lookup("jndiName");

By calling zero-arg getConnection() method on the DataSource


object,java application get a pooled Connection

Connection con=dataSource.getConnection(); //logical Connection


Example:

C:\TOMCAT7\WEBAPPS\conncetionpoolingapp1
+---WEB-INF
web.xml

---classes
FirstServlet.java

+---com
Nit
FirstServlet.class

FirstServlet.java
package com.nit;

import javax.naming.*;
import java.io.*;
import javax.servlet.*;
import java.sql.*;
import javax.sql.*;

public class FirstServlet extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)throws IOException{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
try{

InitialContext context = new InitailContext();

DataSource ds1 = (DataSource)context.lookup("java:/comp/env/jdbc/ods");

Connection con1=ds1.getConnection();
Connection con2=ds1.getConnection();
Connection con3=ds1.getConnection();

pw.println("<br><h1>con1 is logical connection connected to:


"+con1.getMetaData().getDatabaseProductName());
pw.println("<br><h1>con2 is logical connection connected to:
"+con2.getMetaData().getDatabaseProductName());
pw.println("<br><h1>con3 is logical connection connected to:
"+con3.getMetaData().getDatabaseProductName());

con1.close();
}catch(SQLException sqle){
sqle.printStackTrace(pw);
}catch(NamingException ne){
ne.printStackTrace(pw);
}
}
}

web.xml
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.nit.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
</web-app>

Transaction-Management :
What is meant by Transaction? How it is possible to
maintain Transactions in JDBC applications?
Transaction is nothing but an unit of work performed by
the applications. Every transaction should have the
following properties.
Atomicity
Consistency
Isolation
Durability

If your JDBC Connection is in auto-commit mode value is


true, which is by default, then every SQL statement is
committed to the database upon its completion. That
may be fine for simple applications, but there are three
reasons why you may want to turn off auto-commit and
manage your own transactions:

To increase performance

To maintain the integrity of business processes

To use distributed transactions

Transactions enable you to control if, and when, changes


are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical
unit, and if any statement fails, the whole transaction
fails.

To enable manual- transaction support instead of the


auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit(boolean)
method. If you pass a boolean false to
setAutoCommit(false ), you turn off auto-commit. You can
pass a boolean true to turn it back on again.

For example, if you have a Connection object named


conn, code the following to turn off auto-commit:

conn.setAutoCommit(false);
commit & rollback

Once you are done with your changes and you want to
commit the changes then call commit() method on
connection object as follows:

conn.commit( );

Otherwise, to roll back updates to the database made


using the Connection named conn, use the following
code:

conn.rollback( );

The following example illustrates the use of a


commit and rollback object:

DriverConnection.java

package com.nit.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DriverConnection {
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn()throws
SQLException{
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@loc
alhost:1521:xe","system" , "manager");
return con;
}
}

TestCase.java

package com.nit;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.nit.util.DriverConnection;
public class TestCase {
public static void main(String[] args) throws
SQLException{
Connection con=null;
try{
con=DriverConnection.getConn();
con.setAutoCommit(false);

Statement st=con.createStatement();
int count=st.executeUpdate("INSERT INTO STUDENT
VALUES(89,NITSTUDENT2',85)");
System.out.println("Number of Rows are Inserted:"+i);
If(count>0){
con.commit();
}
}
catch(SQLException e) {
con.rollback();
System.out.println(e);
}
}
}

OUTPUT

Number of Rows are Inserted:1

Check The Data in DataBase


SQL> SELECT *FROM STUDENT;
SNO SNAME SMARKS
------- -------------- ----------
25 NIT 89
95 NITSTUDENT 99

package com.nit;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.nit.util.DriverConnection;
public class TestCase {
public static void main(String[] args) throws
SQLException{
Connection con=null;
try{
con=DriverConnection.getConn();
con.setAutoCommit(true);
Statement st=con.createStatement();
int i=st.executeUpdate("INSERT INTO STUDENT
VALUES(89,'NITSTUDENT2',85)");
System.out.println("Number of Rows are Inserted:"+i);
}
catch(SQLException e) {
//con.rollback();
System.out.println(e);
}
}
}

OUTPUT

Number of Rows are Inserted:1

Check The Data in DataBase

SQL> SELECT *FROM STUDENT;

SNO SNAME SMARKS


---------- ------------------- ----------
25 NIT 89
95 NITSTUDENT 99
89 NITSTUDENT2 85
Note:

In Projects to reuse the Transaction we will use Custom Transaction


Management

Use-Case:

You might also like