Sie sind auf Seite 1von 162

JDBC

a)When it is given to begin the execution.


b)In the process of creating first object for the class.
c)When Class.forName()is called.
Q:- How can we develop java application without main method?
Ans:public class DemoApp1
{
static
{
int a=10;
System.out.println(square of a =+a*a);
System.exit(0);
}
}
The above code runs in all java versions up to jdk1.6 and in the
initial release of jdk1.7 but not in other version.
API: Application Programming Interface
Here the word interface is no way related to java interface. It is
used
Having English meaning based/platform;

APIs are base for developers to develop software applications.


Every language technology and framework gives different API.
In c language API mean set of function which is in the form of
header files.
C++ API means set of functions, classes which comes in the
form of header files.
In java API means classes, interfaces, enums, annotations
which come in form of packages.
There are 3 types of API.
(i)

Built-in APIs (given by language/technology/framework)

(ii)

User-Defined APIs (given by programmer)

(iii)

Third party APIs (given by other than above two)


Popular Java APIs(built in api)

Utility api(java.util and its sub package)


Jdbc api(java.sql, javax.sql and its sub packges)
JDBC : =>
Persistence : =>
Saving data for long time and manage data for
long time is called persistence.
The process of saving and managing data for long time is
called persistence.

The data stored in variables, objects of application allocates


memory in different part of RAM only during the application
execution. This data, memory vanished once the application is
completed because RAM is temporary memory. In order to
overcome this problem we should write application data to
secondary memory like hard disk to persistence.
Terminologies:(1)

Persistence store

(2)

Persistence data

(3)

Persistence logic

(4)

Persistence Technology
CRUD/CURD/SCUD
o C-Create(insert)
o R- Read (select)
o U-Update(modify)
o D- Delete

Terminologies:The place where data will be saved


and managed is called persistence store
Persistence Store:The data of persistence store is called
persistence data.
Persistence Operation:-

The insert, update, delete and select


operations performed on persistence data is called persistence
operations. These are also called CURD/CRUD/SCUD
operations.
The logic that is used to perform persistence operation is called
persistence logic.
Eg:- IO Steam code, JDBC code hibernate code.
The technology that can be used to develop persistence logic is
called persistence technologies.
Eg:- JDBC, Hibernate (Framework), spring jdbc(framework)
Every application contains some logic like presentation,
business, service and persistence logic and etc.
The logic that provides user-interface to end user to view
result to supply inputs is called presentation logic.
The logic that generates result is called business logic/service
logic.
The logic that persist data is called persistence logic.
Sample Application: Read student details like no, name, marks (3 subjects)
presentation logic.
Calculate total average Service logic.
Total=m1+m2+m3;
Avg=(m1+m2+m3)/3;

Generating ranks for students service logic.


Display Result Presentation logic.
Save result, inputs to Db table persistence logic
I/O Stream
Java Application

Files

Serialization & Deserialization


Java Application jdbc(sql queries) DataBase
SoftWare(RDBMS)
(oracle, Sybase, mysql --------)
Serialization =>
Process of capturing object data and writing that data
to file is called serialization.
Deserialization :=>
Reading data form file and constructing object having
that data is called deserialization.
Limitations with files as persistence stores: No Security.
Cannot maintain huge amount of data.
No constraints can be applied.
No sql support.

We cannot define relationship.


Update and delete operation are very complex.
Merging and comparison of data is very complex.
To overcome these problems use database software as persistence
store.
The Advantages are: Security
Sql support
Allows to apply constraints, allow to define relationship.
Merging and comparison of data is very easy and etc.
Conclusion: Use files as persistence store in small scale application
Use database software as persistence store in large scale
application.
Eg: Banking application, Insurance application etc.
To get interaction between operating system and external devices
of computer like printer we need support of external device of
computer like printer we need device driver.
\

We need jdbc diver as bridge between java application and


database software. It converts java calls to database calls and vice
versa.
Non java application use odbc driver to interact with database
software.

We cannot use ODBC driver directly in our java applications.

Some jdbc driver internally uses odbc driver support while


interacting with database software. Some other JDBC driver
directly interacts with database software.
We can get jdbc driver from three vendors :(a)

Sun Microsystem (oracle corporation)

(b)

Database Vendor (Recommended)

(c)

Third party vendors.

We can get odbc driver from three vendors.


(a)

Xopen

(b)

Database vendors (recommended)

(c)

Third party vendors.


Jdbc 4.x Api packages.
java.sql, java.sql packages (core packages)
Javax.sql.RowSet, javax.sql.rowset.Serilizable
,javax.sql.Rowset.api(advanced packages)

Continue
2015-03-12

What is the difference between language and technology?


Programming language:These are raw material directly installable
software as raw material having basic features of application
development.
Programming language define syntax (Rule), Symantec (structure)
of programming.
Language is base for creating technology, framework, operating
system and database software etc.
Eg c, c++, java etc.
Technologies:These are software specification
having set of rules and guideline to develop software by using
programming language.
Technology is not installable but technology based software
installable.
Working with these software is nothing but working with
technologies.
Jdbc is technology software specification that gives set of rules
and guidelines to develop Jdbc driver using java language. Jdbc is
not installable. Working with jdbc driver is nothing but working
with JDBC .

There are two types of technology are:(1)

Open technology:These technologies are rules and guidelines

open for multiple vendor companies to develop the software.


Eg:- All jsp, jee technology (jdbc, jndi, servlet etc)
(2)

Proprietary technology:The vendor that has given these technologies are only
allowed to develop software based on the technologies.
Eg:-All Microsoft Technology.

Since all jdbc driver given by different vendor companies are


coming based on the common rules and guidelines of jdbc
technology so we can work with all these jdbc driver in a
common way in the application development.
The interfaces of jdbc API packages represent rules of jdbc
technology and the classes of jdbc API packages represent
guidelines of jdbc technology.
Every jdbc driver is a collection of classes implementing various
interfaces of jdbc Api packages and all these classes contain logic
to interact with sertain database software and to send and execute
sql queries in database software.
Q:- What is jdbc?
Ans :- It is an open java technology given by sun microsystem having
set of rules and guidelines to develop jdbc driver for difference
database software.
ODBC :->
It is an open technology given by Xopen has set of rules
and guidelines to develop odbc driver for different database software.
Every technology gives one API. This API will be used by vendor
companies as rules and guidelines to develop softwares .The same
API will be used by programmers to work with technology based
software in the application development.

Eg. The API of jdbc technology will be used by vendor companies


as rules and guidelines to develop jdbc drivers and the same api
will be used by programmer in application development to
activate jdbc drivers and to develop jdbc persistence logic.

java.sql.Driver (interface)
^
|

extends

sun.jdbc.odbc.jdbcOdbcDriverInterfacd (Interface)
^
| implements
sum.jdbc.odbc
Even though multiple class in every jdbc driver we just know
diver class name in order to activate and use these jdbc driver in
our java application.
Every Jdbc driver is identified with its driver class. It is the class
supplied by vendor company of jdbc driver implementing
java.sql.Driver Interface directly or indirectly.
Upto jdk1.7 we get one built in jdbc driver given by sum
Microsoft in rt.jar file. This jdbc driver is identified with its driver
class .

sum.jdbc.odbc.JdbcOdbcDriver
(package

)|(class name)

The above jdbc driver class implements java.sql.DriverInterface


directly as shown below:Java.sql.Driver(interface)
^
| extends
Sun.jdbc.odbc.JdbcOdbcDriverInterface(interface)
^
| Implements
Sum.jdbc.odbc.JdbcOdbcDriver(class)
Along with window operating system installation we get multiple
ODBC driver every odbc driver is identified with its DSN.
There are three types of DSNs available thses are: (1)

User Dsn :- specified currently logged in user.

(2)

System Dsn : - Spcific to all the window users of a


computer.

(3)

File system Dsn :- Sharable in the network.


Procedure to create dsn for Microsoft odbc driver for oracle

Step 1) Make sure that oracle is installed.


Step 2) Add oracle installation related bin directory to path
environment variable (My Computer)

Step 3) My computer propertyAdvance system settings


environment variables user/System variables variable name:
path
Value: <exiting values>;c:\oracle
xe\app\oracle\porduct\10.2.0\server\Bin;ok(3).
Steps (3) create user DSN for micro soft odbc driver for oracle(window
7/8)
C:\window\syswow64\odbca32userDsn(tab) addMicrosoft
odbc for oracle/oracle xefinished.
Data source name :oraDsn
Description :[dsn for microsoft odbc driver oracle]
User name: scott
Server :
Server:This value is optional while working with local oracle. This
value is mandatory while working with centralize network. (Gaither
Dsn String from admin)
Vendor companies can use one of the five mechanism
/architecture/methodology to develop jdbc driver for different Data
Base software based on the rule and guideline of jdbc technology .
They are :-(1)

Type-1 driver (jdbc-odbc bridge driver)

(2)

Type-2 driver (Native API /partly java driver)

(3)

Type-3 driver (Net protocol/all java driver)

(4)

Type-4 driver (Native protocol/All java driver)

(5)

Type-5 driver (not yet confirmed by sum micro system so there


is no technical name)

Partial Architecture of Type-1 jdbc driver:This type-1 driver is designed to talk with Data base software
directly. It is designed talk the support of odbc driver to interact
with database software.

We can use one type-1 jdbc driver to talk with multiple database
software by take support of multiple odbc driver.
The jdk supplied build-in jdbc driver is given based on type-1
architecture. Its driver class name is
sum.jdbc.odbc.JdbcOdbcDriver.
So for only sun Microsoft is giving type-1 diver along with jdk
software installation .(up to jdk 1.7)
Every java application contain one built in service called
Drivermanager service.
Having the capability to manage set of jdbc dirvers.
TO access these services in our application we can use
java.sql.DriverManager class.

To user JdbcDriver in our java application it must be register with


driver manager service for this we need to keep JdbcDriver class
object in DriverManager service by using register driver
manager.
//Registering jdbc type-1 driver
//creating odbc driver class object
sun.jdbc.odbc.JdbcOdbcDriver obj1=new
sun.jdbc.odbc.JdbcOdbcDriver();
//Register jdbc driver
DriverManager.registerDriver(obj1)
Property of registerDriver(--) method
Public static void registerDriver(java.sql.Driver driver) throws
SQLException
The parameter type of registerDriver(--) method is java.sql.Driver(I), so
we must call that method having implementation class object of that
interface all jdbcdriver class implements java.sql.Driver(I) directly or
indirectly due to this we can call registerDriver(--) having jdbc driver
class object. Notes:Sun.jdbc.odbc.JdbcOdbcDriver(c)
Implement java.sql.Driver(I) directly or indirectly.
Three important statements of method parameter types.

Note: - we cannot create object of interface and abstract classes.


A) If method parameter type is interfaces we call that method having
implementation class object of that interface (refer above)
B) If method parameter is a abstract class. We call that method
having one subclass object of that abstract class as argument.
C) If method parameter type is concrete class, we call that method
having either that class object or one of its subclass object as
argument.
Jdbc application means java application with jdbc code as
persistence logic to manipulate database data.
Jdbc application acts as front end and database software acts as
back end.
What end user see and operate is called front end, what he cannot
see call backend.
Backend(database software) responds based on front end
interaction.
Standard steps to develop jdbc application.
a) Register jdbc driver with Driver Manger Service (Activate jdbc
driver)
b) Established the connection with database software.
c) Create statement object.
d) Send and execute Sql Queries in database software.

e) Gaither results from database software and process the results.


f) Close connection with database software.
Registering jdbc driver is nothing but placing jdbc driver class
object with driver manager service.
This is mandatory to use jdbc driver in our java applications.
Establishing connection means creating communication channel
between java application and database software.
Jdbc statement object acts as a vehicle between java application
and database software.
To send SQL queries to database software to execute sql queries in
database software and to gather result back to java application
Once operation with database software is completed it is
recommended to close connection with database software.
Q:- Write a jdbc application to establish connection between java
application and oracle software using type-1 jdbc driver.
Software Set Up: Java any version (jdk 1.7)
Oracle any version (oracle 11g)
Type-1 jdbc (Built in with jdk software dsn create for Microsoft odbc
driver for oracle (oradsn)
import java.sql.*;

public class ConnTest


{
public static void main(String args[]) throws Exception
{
//Register odbcDriver(type 1)
//Create jdbc diver class obj
sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver();
// register diver
DriverManager.registerDriver(obj);
//Establish the connection with database software
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
system.out.println("Connection not established");
}
else
system.out.println("connection is established");
}//main method closed
}//class closed.
27-02-2015

getConnection method uses given jdbc url , database password details


to use to appropriate jdbc driver, other details while establishing the
connection with database software
Jdbc url syntax
< main protocol >: <sub protocol>: sub name
In case of type-1 driver the url is jdbc:odbc:oradsn
Name of dsn
jdbc main protocol
odbc sub protocol
Oradsn sub name (dsn)
The jdbc driver class name, jdbc url will change based on the
jdbc driver we use and database software we use.
Protocol is set of rules followed by two parties who wants to
participate in communication.
There are two types of protocol.
(1)

Application level protocol


Gives set of rules to get
communication between software services.
Eg: - http, jdbc:odbc

(2)

Network level protocol :

Gives set of rules to get


communication between two physical computer of
network.
Eg: - Tcp/ip.
In the above application
DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger)
method performs.
(1)

Picks up the registered type-1 jdbc driver form DriverManager


service. Based on the protocol jdbc:odbc specified in the url.

(2)

Type-1 jdk dirver uses odbc driver for oracle based on the dsn
that is specified (oradsn).

(3)

Using both driver (Type-1 odbc driver) the connection


between java application and database software will be created
and the jdbc connection object will be return back to the jdbc
connection object will be returned back to java application
representing that connectivity.

Q:Connection
con=DriverManager.getConnction(jdbc:odbc:oradsn,scott,tiger)
When java.sql.Connection is an interface how can we say
DriverManager.getConnection(-, -, -) is returning jdbc
connection object.
Ans:

Jdbc connection object means it is not object of java.sql.connection .


It is the object of that underlying jdbc driver supplied java class that
implements java.sql.Connection(I). Since this class name changes based
on the jdbc driver we use we never specify this class name in our jdbc
aplications.
In type-1 jdbc driver this name is
sun.jdbc.odbc.JdbcOdbcConnection and this class implements java
connection(I) as shown below.

To know class name by object we can use getClass() method.


System.out.println(connection object name:+con.getClass());

Interface reference variable can reference its implementation


class object. DriverManager.getConnection(-, -, -) return the
implementation class object .
Java.sql.Connection(I) and we are referring that object with
java.sql.Connection(i) reference variable (that is con).
Properties of getConnection(-, -, -)
public static getConnection(String url,String user,String pwd)
throw SQLException
The return type of DriverManager.getConnection is
java.sql.Connection that means this method returns
implementations class object of java.sql.ConnectionInterface.
Three type of statements on method return types: 1. If method return type is abstract class then method returns one
subclass object of that class.
2. If method return type is interface then method retrun
implementation class object of that interface.
3. If method return type is concrete class then method return
either that concrete class object or one of its subclass objects.

02-28-2015

Instead of writing two line of code to register jdbc driver with


DriverManager service we can use the following one line of
code for the same purpose.
class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
class.forName(-) load the given jdbc driver class.
In that purpose the static block of driver class executes.
This static block contains logic to create jdbc driver class
object and logic to create jdbc driver class object and logic to
register that object with DriverManager service by calling
DriverManager.registerDriver() method.
The static block of sun.jdbc.odbc.JdbcOdbeDriver class
looks like this.
Static
{
Try
{
JdbcOdbcDriver jdbcodbc=new JdbcOdbcDriver();
DriverManager.registerDriver(jdbcodbcdriver);
}
Catch(Exception)
{
e.printStackTrace();
}

}
Different ways of reading input from keyboard.
1) Using Scanner Class (jdk 1.5 onbord)
2) Using Command line arguments
3) Using user defined system property
4) Using BufferedReader
5) Using java.io.Console (jdk 1.6)
import java.io.*;
import java.util.*;
public class ReadInput
{
public static void main(String args[]) throws IOException
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter Name-1 : ");
String name1=sc.next();
String name2=args[0];
String name3=System.getProperty("myName");
//using stream
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter name-4 :");

String name4=br.readLine();
//Using console
System.out.println("Enter Name-5 : ");
Console cons=System.console();
String name5=cons.readLine();//display value
System.out.println(name1+" "+name2+" "+name3+" "+name4+"
"+name5);
}>javac ReadInput.java
}> java DmyName=Raja3 ReadInput Raja2
Setting command line argument
Setting System property value
Once specified passing command line argument is mandatory
Once specified passing system property is optional.
Q: - can you explain different way of registering jdbc DriverManager
with DriverManager service
Approach-1: sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver(obj);
import java.sql.*;
public class ConnTest
{
public static void main(String args[]) throws Exception
{ //Register odbcDriver(type 1)

//Create jdbc diver class obj


sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver(); // register diver
DriverManager.registerDriver(obj); //Establish the conncection with
database software
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
In process of creating first object to any class jvm load that class
and executes static block of that class.
In the above code same jdbc driver will be register with
DriverManager service.
First time because of static block of jdbc driver class.
Second time because of explicit call given to
DriverManager.registerDriver(-) method.

Note: - Registering same jdbc driver is a bad practice so the


approach-1 is bad approach.
Approach-2: DriverManager registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
Note: - This approach is very much similar to approach -1 so it is
not recommended to use.
DriverManager.registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
import java.sql.*;
public class ConnTest2
{
public static void main(String args[]) throws Exception
{
DriverManager.registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)

{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach-3
sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver();
import java.sql.*;
public class ConnTest3
{
public static void main(String args[]) throws Exception
{
sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver();
database software
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)

{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
} }
Approach-4
new sun.jdbc.odbc.JdbcOdbcDriver();
Approach-4 is similar to approach-3 so it is not recommended to
use
Note: In approach- 3&4 the driver will registered only for one time but
explicitly created object of driver class will be wasted.
new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");

import java.sql.*;
public class ConnTest4

{
public static void main(String args[]) throws Exception
{
new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach-5
public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver
{
public static void main(String args[]) throws Exception
{

Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
In the above code when jvm load contest class it also loads its
super class called Driver class in this process static block driver
class execute and driver will be registered.
The above code is not recommended because it does not let our
application class to extends from other class like from applet,
HTTPservlet
import java.sql.*;
public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed

}//class closed
Approach-6
class.forName(sun.jdbc.odbc.JdbcOdbeDriver)
This is a recommended approach because it registered the driver
only for one time and does not create any west object for driver
class
import java.sql.*;
public class ConnTest6
{
public static void main(String args[]) throws Exception
{
if(Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach=7

public class contest


{
public static void main(String args[]) throws IOException
{
Class.forName(args[0])
Connection con=new
DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger);
import java.io.*;
import java.sql.*;
class ConnTest7
{
public static void main(String args[]) throws Exception
{
Class.forName(args[0]);
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");

}//main method closed


}//class closed
Approach-8
Public class contest
{
Public static void main(String args[]) throws Exception
{
String driver=System.getProperty(myDriver);
Class.forName(driver);
Connection
con=DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger)
;
}}
This is similar to approach-7 so not recommended to use.
import java.io.*;
import java.sql.*;
class ConnTest8
{
public static void main(String args[]) throws Exception
{
String driver=System.getProperty("mydriver");
Class.forName(driver);

Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
>javac ConnTest8.java
>java Dmydriver=sun.jdbc.odbc.JdbcOdbeDriver ConnTest8
Approach-9
As part of DriverManager class initialization it attempt to load jdbc
driver class that are there in fixed system property so driver will be
registered automatically.
Class contest
{
Public static void main(String args[]) throws IOException
{

Connection
con=DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger)
;
}
}
import java.sql.*;
public class ConnTest10
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("The conncetion is not establish");
}
else
System.out.println("the conncetion is establish");
}//>javac ConnTest9.java
}//>java Djdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver ConnTest
Approach-10

Since type-1 driver is built in driver of jdk there is no need to


registering that driver with driver manager service.
Public class TestConn10
{
Public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConncetion(jdbc:odbc:oradsn,scott,tiger)
;
import java.sql.*;
public class ConnTest10
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("The conncetion is not establish");
}
else
System.out.println("the conncetion is establish");

}
}
Write a jdbc application that use stud
details based on the given start end rang of student no.
Select * from student where sno>=100 and sno<=400
//selectTest1.java
import java.sql.*;//for jdbc api
import java.util.*;//for Scanner
public class SelectTest1
{
public static void main(String[] args) throws Exception
{
//Read inputs
Scanner sc=new Scanner(System.in);
System.out.println("Enter start range of student no");
int stno=sc.nextInt();
System.out.println("Enter end range of student no");
int endno=sc.nextInt();
//register jdbc driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Establish connection with db s/w

Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
//create statement object
Statement st=con.createStatement();
//prepare SQL Queries
//select * from student where sno>100 and sno<=400
String qry="select * from students where sno>="+stno+" and
sno<="+endno;
System.out.println(qry);
//send and execute sql Query in db s/w
ResultSet rs=st.executeQuery(qry);
//process ResultSet
int cnt=0;
while(rs.next()!=false)
{
cnt=1;
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));
}//while
if(cnt==0)
System.out.println("No record found");
//close jdbc objs

rs.close();
st.close();
con.close();
}
}
Q: - Write a jdbc application to get student details based on the given
city name.
Q: - Write a jdbc app empno, ename, sal, job details of employee based
on the given dept no.
select empno, ename, sal, job from emp where deptno=10;
while processing resultSet use those index for column value in order
they stored in result set obj not in the order they are available in
database
While retrieving value from Resutlset record we can use
rs.getString() method if u dont know the data type.
We can call rs.getxxx(--) method to retrieve the value of record
either with cols name of cols index.
Assignment:-1
Write a program that returns students details based on given initial
characters of student Name?
Assignment: -2

Write a program that returns Employee details based on the


given three designation.
Q: - When java does not support pointer why does it throws
NullPointer exception
When we invoke method on reference variable that holds null
value we will get NullPointerException.
Date d=null;
d.getYear();//Throws NullPointerException
-> Here the word pointer is no way related to c/c++ pointers. It is
purely used by having Dictionary meaning indicating method is on
reference variable that points to null value.
SOLUTION:
Date d=null;
d=new Date();
d.getYear(); //Does not throw NullPointerException

import java.sql.*; (implicit pkg import)


import java.sql.DriverManager;
Important java coding standards;
1) Write proper comments.
2) Avoid implicit pkg imports prefer explicit pkg imports

Ex: - import java.sql.Connection; //Explicit pkg import.


3) Take variable, method, class, interface names with self
description.
4) Check for Not Null before calling methods on reference
variable to avoid NullPointerException permanently.
5) Do not declare the Exception to be thrown using throws .
Always catch and handle exception using try/catch blocks.
6) Place multiple catch block followed try block to handle both
known and unknown exceptions.
7) Close stream, jdbc objects in finally block (not in try, catch
blocks) because these blocks execute irrespective of exception
that is raised in try block.
8) Always place java class/interface in a pkg.
9) And etc
Q. Write a jdbc application to get students details based on
given initial characters of students
Solution: Sql Queries :- select * from students where sname like 'N%';

3-5-2015

Q: - Write a jdbc application to get count of emp table record


Select count(*)from emp;
employee name,jobdetails for the emp who is having highest salary
select ename,empno,job from emp where sal=(select max(sal) from
emp);
If resultSet object contain exactly one record then process the resultSet
using if(rs.next) method.
If ResultSet contain zero or more record then process that
RecordSet by using while(rs.next()) method.
Once we close jdbc connection it automatically closes relevant
statement, ResultSet object.
Prototype of createStatement()
Public Statement createStatement() throws SQLException
Prototype of executeQuery(--)
Public ResultSet executeQuery(String qry) throws
SQLException
To send and execute non-select sql query in database software we
use executerUpdate() method. This method return numeric value
representing number of record that are affected it will return
integer.

Q:- Write a jdbc application to delete student details based on


given student no.
Delete is a non-select sql query so use executeUpdate() method
for sql query execution.
Refer->aap-2 page no19,20
There is no necessity of dealing with ResultSet object.
Sql query that is execute through in database s/w through sql
command it is not auto committed.
Sql queries that is executing by coming from jdbc application
execute in data base s/w by enabling auto commit.
Write a jdbc application to update student name, address, based on
given student number.
Update students set sname=raja,sad=Delhi where sno=901;
App-5 page- 22 and 24
2015-03-06
Notepad, notepad++, editplus are editors
Eclipse, MyEclipse, NetBeans and etc, are IDEs
IDE provides total environment that is required for the
development and integration of the project.
Eclipse: Type: IDE for java environment
Vendor: Eclipse or

Version: 4.4 (Eclipse luna)


Open source (freeware)
To download s/w : ww.ecllipse.org
(as zip file: Extract zip file for installation)
Two flavors of Eclipse
1) JSE flavor (sdk)
2) Jee flavors
www.nataraz.in/software
Q: - Write a jdbc application to insert record into student table while
gathering details from end users?
Procedure to application by eclipse IDE
Step-1) Launch eclipse ide by choosing its workspace( a folder where
all project will be saved) folder.
Step-2) Create java project.
File->new->project->Project name (jdbc proj-1)finish
Step- 3 Develop the above jdbc application in com.nt package of src
folder.
a) Create package(Right click on src folder new packagecom.nt
b) Right click on com.nt package newclassname:InsertTest
InsertTest.java
Refer App4 page no:20.
Ctrl+space bar gives main()

Ctrl+shift+o
Step-4 run the application
Right click in source file run as java Appuse run as button of the
menu bar.
To change JRE of the java project in eclipse
Right click on project build path libraries table remove existing Jre
Add library JRE System library next
Installed jreadd-standard vm next JRE home[c:\porgram files
(x86)\....--> select jdk finish.
xany
toString () method called on exception object just used to called
exception object that is raised.
printStack() method called on object elaborated details that is
raised.
When exception is raised in java method the stack memory of the
method will be filled up with exception related messages. TO print
those messages on console monitor we need to use printStackTrace()
method.
From jdk 1.7try with resource is intro where the resource in try will
be close automatically at the end of try without closing them explicitly.
Try(Scanner sc=new Scanner(System.in))
{

..
}
The Sc will be closed automatically at the end of try block.
Using try with Resource for jdbc code
Class InserTest
{
psvm()
{
try(
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver))
{
catch(exception e)
{
e.printStackTrace();
}
try(conncetion con=DM.getConnection(-,,);
Statement st=con.createStatement())
{
Int res=st.executeUpdate(delete from student where sno=10);
If(res==0)
Sop(record not delete);

Else
Sop(record deleted);
}//main
}//class

2015-03-07
Notepad, notepad++, editplus are editors
Eclipse, MyEclipse, NetBeans and etc, are IDEs
IDE provides total environment that is required for the
development and integration of the project.
Eclipse: Type: IDE for java environment
Vendor: Eclipse or
Version: 4.4 (Eclipse luna)
Open source (freeware)
To download s/w : wwweclipse.org
(as zip file: Extract zip file for installation)
Two flavors of Eclipse
3) JSE flavor (sdk)
4) Jee flavors
www.nataraz.in/software

Q: - Write a jdbc application to insert record into student table while


gathering details from end users?
Procedure to application by eclipse IDE
Step-1) Launch eclipse ide by choosing its workspace( a folder where
all project will be saved) folder.
Step-2) Create java project.
File->new->project->Project name (jdbc proj-1)finish
Step- 3 Develop the above jdbc application in com.nt package of src
folder.
c) Create package(Right click on src folder new packagecom.nt
d) Right click on com.nt package newclassname:InsertTest
InsertTest.java
Refer App4 page no:20.
Ctrl+space bar gives main()
Ctrl+shift+o
Step-4 run the application
Right click in source file run as java Appuse run as button of the
menu bar.
To change JRE of the java project in eclipse
Right click on project build path libraries table remove existing Jre Add
library JRE System library next
Installed jreadd-standard vm next JRE home[c:\porgram files
(x86)\....--> select jdk finish.

xany
toString () method called on exception object just used to called
exception object that is raised.
printStack() method called on object elaborated details that is
raised.
When exception is raised in java method the stack memory of the
method will be filled up with exception related messages. TO print
those messages on console monitor we need to use printStackTrace()
method.
From jdk 1.7try with resource is intro where the resource in try will
be close automatically at the end of try without closing them explicitly.
Try(Scanner sc=new Scanner(System.in))
{
..
}
The Sc will be closed automatically at the end of try block.
Using try with Resource for jdbc code
Class InserTest
{
psvm()

{
try(
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver))
{
catch(exception e)
{
e.printStackTrace();
}
try(conncetion con=DM.getConnection(-,,);
Statement st=con.createStatement())
{
Int res=st.executeUpdate(delete from student where sno=10);
If(res==0)
Sop(record not delete);
Else
Sop(record deleted);
}//main
}//class
Can be execute both select and non-select query by using single
method call Yes possible by using execute() method
This method return type is Boolean.
Prototype

.
Public Boolean execute(String qry) throws SQLException
This method returns true when it executes select SQL Query.
To get ResutlSet of this select SQL Query use getResultSet()
method.
This method returns values that represents number of records
that are affected because of this non-select Query use
getUpdateCount() method
For example application - ref-6 page no 24.
358
Working with execute method is not industry standard because it does
not give sql result directly more ever we need to call method separately
go gather sql query result (like getResultSet(), getUpdateCount)
Conclusion:
Use executeQuery(_) to send and execute select SQL QUERY
IN database s/w.
Use executeUpdate(-) to send and execute non-select sql
query in database s/w
Jdbc application to create database table in database s/w.
Note: - create table, drop table and alter table are non-select query.
So we should use executeUpdate () to send and execute these method
in sql query database s/w.

In real scenario ddl query execution does not takes place


through jdbc code only temp table will be created and dropped to
jdbc code
In every company separate db team will maintain to design the
table will be maintain this team will responsible to execute ddl
form sql prompt
Write a ddl application to
Executing ddl query through jdbc application is not industry standard
because the end result of these queries execution is not same in all the
driver more ever db team is responsible to design table for the project.
Jdbc application is not alternate for sql prompt thse are front end
application interacting with database software support end user.
Miscellaneous command like desc <table-name> cannot be
executed through jdbc application.
In one jdbc application we can have multiple connection,
statement , ResultSet 0bj using one connection object you can
create one or more statement object
Using one statement object crate one or more ResultSet object
U can use one ResultSet object to send and execute one or more
sql queries. In database s/w.
Q can we develop java application without user defined class?
Possible with enum.

Every enum is special java class internally.


2015-03-09
Understanding internals of DriverManager.getConnection(-,-,-)_
Connection
con=DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger);
1) Prototype
Public static Connection getConnection(String url,String user,
String pwd);
getConnection(-,-,-) is the static method DriverManager()
getConnection(-,-,-) getRegister jdbc driver class object based
on the given url(protocol & sub name) and calls connect() on
that object.
The connect() of jdbc driver class creates and returns
implementation class object Connection(I) to getConnection(,-,_) method and getConnection(-,-,-)returns object to our
application.

Understanding internals of createStatement() method

Satatement st=con.createStatement();

(a)createStatement() is non-static method declared in


java.sql.Connection(I).
Prototype: Public statement createStatement();
(b)

createStatement contains implementation in the

implementation class of java.sql.Connection(I) that is


sun.jdbc.odbc.JdbcOdbcConnection(c) in type-1 driver.
(c) createStatement() method definition contains logic to create and
the implementation class object of java.sql.Statement(I) .That is
object of sun.jdbc.odbc.JdbcOdbcStatement(C) in type-1 diver.
Understanding the internals of executeQuery(-) method
ResultSet rs=st.executeQuery(select U from students);

1) executeQuery(-) is non-execute(-)is non-static method declared


in java.sql.Statemnet(i)
Prototype:
public ResultSet executeQuery(String qry) throws SQLException
2) executeQuery(-) is implemented in jdbc driver supplied java class
that implements java.sql.Statement(I). In type-1 driver that class
name is
sun.jdbc.odbc.JdbcOdbcStatement.
3) executeQuery(-) internally calls getResutlSet() method.
4) This getResutlSet() contains logic to crate and return the
implementation class object java.sql. ResultSet(I).

2015-03-10
There are 5 mechanisms/architectures to develop jdbc drivers based on
the rules and guide lines of jdbc technology
a) Type-1 driver (Jdbc odbc bridge driver)
b) Type-2 driver (Native API /Partly java driver)
c) Type-3 driver(Net protocol /All java Driver)
d) Type-4 driver(native protocol/ All-.java driver)
e) Type-5 driver(No nick name) (Not officially confirmed by Sun
Ms)
All odbc drivers and some jdbc drivers (type2) locate and
communicate with Db software by using vendor DB library.
In windows environment this vendor db library comes in the
form of .dll file along with Db software installation. (in oracle
it is oci.dll)
Every odbc driver and every vendor db library is specific to one
DB software.

Advantages
One Type-1 driver can interact multiple database software by
taking the support of odbc drivers , vendors db libraries
Since odbc drivers ,vendor db libraries are available for all db
software we can use this driver to interact with All Db software
This is built-in driver of jdk so there is no need of arranging this
driver separately.
Disadvantage
This driver performance is poor so not suitable for big
application.
Since vendor DB libraries are required at client side we cannot
use driver for untrusted applet to DB software communication.
This is not industry standards jdbc driver.
Suitable for testing apps
Removed from jdk from java 8 onward.
This driver must be arranged separately.

Applets are two types:1) Trusted Applet


(it perform read and write operation on file system.
2) Un-Trusted applet
Cant perform read and write operation on file system.(No virus).
When we install either complete oracle or client oracle (that
contains only sql plus we will get vendor db of oracle).

Type-2

Advantages: 1) No odbc drivers are required

2) Gives little bit good performance compare to type-1 driver.


Disadvantage
1) This driver performance is not good for large scale projects.
2) Since vendor DB library is required ate client side, this
driver cannot be used for untrusted applet to dB software
communication.
3) This driver is not industry standard diver.
4) For every DB software we need separate type-2 jdbc driver.
Type-4

Advantages:
1) This gives good performance compare to type-1, type-2
divers and suitable for large scale project
2) Totally developed in java so it is platform independent.

3) No odbc drivers, vendors DB libraries are required at client


side so this driver is suitable for untrusted Applet to DB
software communication.
4) This driver can be downloaded dynamically to our
computer from internet.
5) This driver industry standard driver.
Disadvantages;
1) For every DB software we need separate tupe-4 driver
3) We must arrange these drivers separately
Jdbc connection pool is a factory that conatains set of readily available
jdbc connection objects before actually ebing used. The advantage are:
Gives reusability of jdbc objs.
With min number of jdbc connection objects we can make max
clients to interact with DB software
Programmers need not to worry about creating, managing and
destroying jdbc con objs, All These operations will be taken care
by jdbc connection pool.

All connection objs of jdbc con pool represents connectivity with


same DB software.
Jdbc con pool for oracle means all con objs represents
2015-03-11

connectivity with same oracle dB software

w.r to diagram
1) Server uses type-1/2 /3/4 driver to interact with database s/W
And create jdbc con objs in the jdbc con pool
2) Client app uses type3 driver interact with server and to get con
obj from jdbc con poo.
3) Client uses that con obj to create other jdbc objs and to develop
persistence logic
4) Client app releases the con obj back to jdbc con pool and that obj
becomes free to give service other clieents.

Proxy dummy item that represent present until real items come.
Proxy server talks with the database s/w on behalf of client
applications

There are two types of connection


a) Direct jdbc connection (created by porgrammser manually)
Class.forName(.);

Connection con=DM.getConnection(-,-,-);
b) Pooled connection(Gatherred from jdbc conn pool)
For related information of all jdbc drivers refer page no-8 to16
What is jdbc driver that u have used in project if your project is
standalone/desktop app talking with database s/w or two-tier app
running outside the server (webserver/proxy server) then use type4/5/
jdbc driver
If u r project web application, enterprise app, 3-tier app , ntier app running from the server then use type 3 with type4 or
type3 with type5 jdbc direr
Note: - Here type 4/5 driver will be user dot create jdbc con
objs in jdbc con pool and type3 driver will be used to get con
objs from jdbc con pool.
Q: -What is the difference between path and class path?
Ans: PATH:
It is OS command , can be used in all languages and technologies.

To make .exe, .bat, .cmd files of certain folder executable from


any location of computer we need to worik with PATH
environment variable (without doing physical copying)
It is not java command, so it can be use anywhere.
Example:Problem: E:\Demo
|run.bat
Run.bat
Date
Time
Ver
Dir
E:\Demos?run.bat(success)
E\>run
Run is not an internal or external command (problem)
Solution
.
Add the address of run.bat (E:\Demos) to PATH environment
variable.
Computer properties adv sys settings environement
variables user/system variables

Variable name: PATH


VALUE:E:\Demos;<existing values>;.
od(3)
D:\Demos>run(success)
E:\run<success)
C:\> Run (success)
Batch(.bat) allows us to group set of commands into single unit.
Javac, java, javap, javah and etc.. are the .exe files of
<java_home> \bindirectory, so to use them from any folder
our computer we need to add<java_home>\bin directory to
PATH environment variable.
Important points about environments variable
1) These names are not case sensitive
2) Do not value to environment variables form cmd prompt,
set form mycomputer prompt
3) Separate multiple values added to environment variable
with ; symbol
4) User variable are specific to currently logged in windows
user, system variables are common to all windows users.
5) New values added to environment variables are not visible
old cmd prompts
6) Always add new values at the beginning of existing values.
2015-03-12

classpath
if java app uses new apis or third parties apis then the new
api/third party related directories or jar files must be added to
classpath in order to make java tools (javac ,java, .) recognizing
and using those apis.
It is a java command and cannot used outside the java.
Example
Problem:
User-defined API /third party api
E:/Demo1
|wish.java
Wish.jva
package con.nt;
public class wish
{
public String sayHello()
{
return good morning;
}//>javac d . wish.java
}
Main App
MainApp.java

Import com.nt;
Public class MainApp
{
Public static void main(String args[])
{
Wish w=new Wish();
System.out.println(w.sayHello());
}}
D:\work> javac MainApp.java(x)
Error: Can not find symbols com.nt, wish, sayHello
Solution: The address location of com.nt pkg(E:\Demo) folder to
ClassPath Environemnt variable.
ClassPath value=E:\Demos1;.
Ok(3).
D:\work>javac MainApp.java(success)
D:\work>java MainAp(success)
Jar file: jar archieve file(java level zip file)
Creating jar file representing apis
E:\Demos1>jar cf NtLib .
C =create jar file.
F=specify the jar file name.
To see content of the jar file
E:\Demos1\jar tf NtLib.jar

tGives table of content.


Adding jar file to classpath
Variable name :CLASSPATH
Value:E:\Demos1\NtLib.jar;<existing values>;
Ok(3).
We can also add NtLib.jar file to <java_home>\jre\lib\ext folder.
D:\work>javac MainApp.java
D:\work>Java MainApp
Note : types of class loader
CLASSPATH

<JAVA_HOME>\JAR\LIB\EXT
FOLDER

Allows both directory, jar file

Allows only jar file

Visible to multiple installation of

Specific to each jdk.

jdk.
New values are not visible in old

Visible to old command p

command prompt
These values will be used by

These values will be used by

System class loader

extension class loader.

Set of packages together is called one api.


Set of apis together is called one library.

Jar files represent libraries.


There are 3 classloaders in jar
(a)

To load the classes from jdk libraries (rt.jar)

(b)

Extension ClassLoader

To load the class from the libraries of


<java_home>\jre\lib\ext folder
System classLoader
To load the classes from the libraires (directories/jar files)
added to CLASSPATH environment variable.
How can you execute java app any folder of a computer?
Add the address location of a .class file to CLASSPATH
environment variable.
D:\Work
| TestApp.java
TestApp.java
Public class TestApp
{
Public static void main()
System.o.pln(hello);
}
}
D:\work> jvac TestApp.java
Variable name classpath value:D:\work1:

What is the difference between physical database s/w and logical


database.
Logical db is a logical partition of physical db s/w .Each logical DB
contains Db tables , pl/sql procedures, function and tec
In one physical DB s/w (like oracle ,mysql) we can create
multiple logical DBs for multiple projects of a company on 1
per project basis.
In oracle we get one default logical DB and it is identified with
its SID(Service id).

We call type-1\type-2 jdbc drivers as thick drivers because


they need more component at client side while using.
We call type4\type5 jdbc driver as thin drivers because they
directly talk with DB s/ws without taking support any
components.
The oracle corporation SUPPLIED TYPE2 JDBC DIRVER FOR
ORCALE ID CALLDED Oracle Oci driver.
The Oracle corporation supplied type4 jdbc driver for oracle is
called Oracle thin driver.

(oracle corporation supplied type-4 mechanism based jdbc driver for


oracle)
Mechanism : type 4
Target Database software: oracle
Jdbc driver class: oracle.jdbc.driver.OracleDriver (0r)
oracle.jdbc.OracleDriver
Jdbc url:
jdbc:oracle(protocol)thin(subname):@<host>:<port no>(host name
and port number of oracle):<sid>
Jar files:
oracle 8i:classes111.jar
oracle9i: classes12.jar
Oracle10g:ojdbc14.jar
oracle11g:ojdbc6.jar.
Most of vendor are giving jdbc drivers in the form of jar file as
shown above
All software installed in our computer will reside in different
s/w ports. Every s/w port is identified with its port number. In
windows operating system based computer we have 65535
software ports in that 1024 are reserved for operating system

services. All externally installed software will run on other


ports in the range 1025 to 65535;
Oracle default port no: 1521
MySQL default port no :3306
To refer a computer being from that computer we use the term
localhost.
Procedure to develop jdbc Application by using oracle thin
drive.
Step-1) Gather oracle thin driver details.
Step-2)Add odbc14.jar or odbc6.jar file classpath.
Variable name: Classpath or in

<java_home>\jar\lib\ext

folder
Full path:- C:\Program Files\Java\jdk1.7.0_76\jre\lib\ext\[past here]
Value:
c:\orcleexe\app\orcle\porduct\10.2.0\server\jdbc\lib\odbc14.jar;<e
xisting value>;.
--ok(3).
Step3> Develop jdbc App using oracle thin driver
SelectTest.java
.

.same as previous app

but write following lines of code to register jdbc driver and to


establish the conncection.
//register oracle thin driver with DriverManager service
Class.forName(oracle.jdbc.driver.OracleDriver);
//establish the connection
Connection
con=DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:
xe,scott,tiger);
jdbc:oracle=protocol
thin=subname
:@localhost:1521 host name and port no
Setp4:Work with Oci driver details
(oracle corporation supplied type2 mechanism based jdbc diver for
oracle)
Driver class name: oracle.jdbc.driver.OracleDriver (or)
oracle.jdbc.OracleDriver
url: jdbc:oracle:oci8:@<sid>
jar file : Same as thin diver.
Example application:
All steps are same as oracle thin driver but use the following jdbc url in
DriverManager.getConnection (-,-,-) method.

Connection con=DriverManager.getConnection
(jdbc:oracle:oci8:@xe,scott,tiger);
( jdbc:oracle) protocol
sid (xe)
If the subname is thin in the URL then the oracle thin driver
will be used to establish the connection.
If the subname is oci8 in the URL then the oracle oci driver
will be used to establish the connection.
Jar file added to the classpath are not visible to the projects
created in the IDE but the jar files added to the
java_home\jar\lib\ext folder are visible to the same.
To add jar file (like ojdbc14.jar) to the project of Eclipse IDE
use Right click on the project Build path add external
achieves browser and select the jar file (ojdbc14.jar)
While working with any jdbc driver we need to gather
a) Driver class name
b) Jdbc url
To create jdbc conn pointing to any database s/w we need 4
jdbc properties
a) Driver class name
b) Jdbc url
c) Database user name

d) Database password
The class name of jdbc object will change based on the jdbc
diver we use so we never specify them in our Apps but we
refer the object of those classes by using common jdbc api
interface reference variables.
Java.sql.Statement(I)
^
|extends
Java.sql.PreparedStatement(i)
^
| extends
Java.sql.CallableStatement(I)
There are 3 statement object in jdbc programming
a) Simple statement object
(it is the object of jdbc driver supplied java class that
implements java.sql.Statement(I));
b) PreparedStatement object
(it is the object of jdbc driver supplied java class that
implements java.sql.PreparedStatement object.
c) CallableStatement object
(it is the object of jdbc driver supplied java class that
implements java.sql.CallableStatement. object

2014-03-14

LoginAPP
Checks identity of a user by taking the given username and password
details .Also verifies them against Database table.
DB table in oracle
Saq> create table userlist(uname verchar2(20), pwd verchar2(20));
Sql> insert into userlist values(raja,rani);
Sql> insert into userlist values(king,kingdom);
Sql Query of the Application
Sql> select count(*) from userlist where uname=raja and pwd=rani1
Count(*)
0 (Invalid credentials)
LoginApp.java(refer page no-26 application no-8)

What is sql injection problem?


Changing the behavior or sql query and application by adding special
sql instruction (like --) to the query along with the input values is
called raising sql injection problem. Hackers use this technique to get
into various accounts by supplying correct user name and wrong
password.
Respect to application -8 of booklet.

Java LoignApp
Username :raja - Password: hyd (wrong password)
Output : valid credentials (sqlinjection problem)

In real scenario persistence logic will not be placed directly in main

application like main method persistence will be placed in separate


class called DAO class (Data Access Object class) the java class that
separate persistence logic form other logic it makes that logic as
flexible logic to modify and also has reusable logic is called DAO class.
JdbcProj2
| src

|com.nt
|StudentDAo.java
|MainApp.java
package com.nt;

import java.sql.*;
public class StudentDAO
{

Connection con=null;
public void makeConnection()
{

try{
Class.forName("oracle.jdbe.driver.OracleDriver");
//establish the connection

con=DriverMananager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
}//try

catch(Exception e)
{
e.printStackTrace();

}//catch

}//makeConneciton()

public void getStudentDetails(String city)


{
try{

Statement st=null;
if(con!=null)
st=con.createStatement();
ResultSet rs=null;
if(st!=null)
rs=st.executeQuery("select * from students where sadd="+"'"+city+"'");
if(rs!=null)
{

while(rs.next())
{
System.out.println("rs.gtInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

}//while
}//if
//close objs
if(rs!=null)

rs.close();
if(st!=null)

st.colse();

}//try

catch(Exception e)
{

e.printStackTrace();

}
}//getStudntDetails

public void closeConnection()


{
try
{

if(con!=null)
con.close();

catch (Exception e)
{

e.printStackTrace();
}

}//close connection
}//class

package com.nt;
public class MainApp
{

public static void main(String args[])


{

//create obj DAO class


StudentDAO dao=new StudentDAO();

//call mehods

dao.makeConnection();
dao.getStudentDetails("hyd");
dao.closeConnection();
}//main
}//class

Assignment:
Q: = By using DAO style implementation get the emp details form emp
table who is having given nth highest salary.

When java app sends sql query to databse software ,the database engg of database s/w performs 3
operations on that SQL Query
1. Parse operation
2. Execution operation
3. Fetch operation

Parse-> In this operation the given query will be splited into tokens and the syntax of the query
will be verified by compiling SQL QUERY;

EXECUTE: - The Parsed Query will Optimized and will be executed in database software.
Fetch: - The results of executed SQL Query will be gathered from database software and will be
sent to java application client application.
Simple Statement obj sends raw/static SQL Query to database software , i.e given query goes
to database software directly wit out any conversions.
When use simple statements object to execute same SQL Query in database software for
multiple times either with same values or different values.
a) Same Query goes to database s/w for multiple times from java application.
b) Same query will be parsed in db s/w for multiple times.
c) Same query will be executed in db s/w for multiple times either with same values or diff
values.
d) Same query output will be fetched out from db s/w for multiple times.
Performing a), b) operation on same query for multiple times is unnecessary, But
performing c), d) operations on same query for multiple times is necessary, but we can
avoid a), b) operation happing for multiple times when we work with simple statement
object, Due to this we can say simple statement object is not suitable for executing same
query for multiple times with different values or same values.
Example:Railway Resrervation App that book 100000 tickets per day should execute same inser query for
`100000 times to maintains passenger details.
a) Same insert query goes to Db s/w from java app to database software for 1,00,000 times:
100000*0.1=10,000sec
b) Same insert query will be parsed in database software for 100,000 times:
1,00,000*0.1sec=10,000secs
c) Same insert queruy will be executed in database software for 1,00,000 times wither with same
or diff values:100000*0.1=10,000secs
d) Same insert query output will be fetched out for 100000 times : 100000*0.1=10,000secs

Performing a), b) operations on same for multiple times is unneccassary on same query, but this
cannto be avoided while working with simple statement object..

Limitations with simple statement object


Not suitable to execute same query multiple time either with same values or different values (
Gives performance problem)

May Raise SQL injection problem.

Framing query by involving variable sin complex because


we need to convert java values to sql values in this process.

Inserting date values in the in database table by collecting


values date values in different pattern in complex process.

Inserting large object (files) is not possible.

Improves network traffic between java application and


database s/w .

To overcome all these problem we need to work with percompiled sql query with support of jdbc
perparedSatement objcect.

Pre-compiled sql query/Dynamic sql query


The sql query tahat goes to db s/w from client app with
or without values and becomes parsed or comiled
irrespective of ites executeon is called per-compiled sql
query.

Jdbc prepaearedStatement object represents this percompiled sql queryo of sb s/w being from java app and
this oject can be used
a) To assing multiple set of values to query params.
b) To execute query for multiple times either with same
values or diff values
c) To fetch the query results for multiples times.
Simple Statement object deals with static /raw sql
query where as PreparedStatement obj with precompiled sql query.
The above Railway ticket reservation example with
PreparedStatement obj
a) Insert query oges to Db s/w from java app only for one
time

:1*0.1=0.1 sec

b) Insert query will be parsed /compiled in databse s/w only


for one time

: 1*0.1=0.1 sec

c) Java app assigns multiple sets values to insert sql query


and executes that query for multiple times either with
same or different values :1,00,000*0.1=10,000 secs
d) Same insert query output will be fetched out for multiple
times:

1,00,000*0.1=10,000secs

Here a), b) operations are taking place on insert query only 1


time. This improves performance.
PreparedStatment object suitable for executing same
query for multiple times either with same values or
different.
Based on the above discussion we can say PreparedStatement
objet is useful in the development of ticket reservation,
registration and search activities related application
development.
Procedure to work with PreparedStatement object;Step-1 ) Prepare SQL Query with place holders /parameters (?)

String qry=insert into students values(?,?,?);[parameters


represent (?) Positions in sql query for which values can be set
latter]
Setp-2) send sql query to DB s/w and make that query as percompiled sql query in database s/w and get PreparedStatement
representing that per-compile object query.
PreparedStatement ps =con.prepareStatement(qry);
Con.prepareStatement(0) method
a) Sends given SQL Query to DB s/w
b) Makes DB Engg to compile/parse that Query and also to
make that query as per-compiled SQL Query.
c) Create and Returns PreparedStatement object back to java
application representing pre-compiled sql query of
database s/w.
Step: -3) set values to Query params/place holders(?) of precompiled Query using setxxx(-) methods.
Ps.setSPs.setInt(1,1001);
Ps.setString(2,raja);

Ps.setString(3,hyd);
Step:-4) Execute the above pre.compiled sql query of
database s/w.
Int result=ps.executeUpdate();
Step5) Process the result.
If(result==0)
Sop(record not inserted);
Else
System.out.println(Record inserted);
Step: -6) To execute the above query for multiple with diff
values repeat step3 to step 5 for multiple times.
Step:-7) close jdbc object.

Write a jdbc app to gather and insert n number of stuendts details in


database table

Here we need to execute same insert SQL Query with diff values
for multiple times, for this we need to use per-compiled SQL
Query with the support of jdbc PreparedStatement object.
Referr application
IN THE development logic it is always recommended to sql query

at the top of class as constant value(static final variable var)


Ex: -private static final String INSERT_STUDENT_QRY
Dont place * symbol in select sql query, Always write col names
in select sql query.
Select * from student bad practice( if we add new col in db
table then problem will come)

Select sno,sname,sad from student good practice.


We can use preparedStatement object for both select or nonselect query exection.
Pre-compiled query represented by preparedStatment object can
be there with parameters or without parameters.
Executing select query by using preparedStatement object.

PreparedStatement ps=con.prepareStatement(Select * from Student);


ResultSet rs=ps.executeQuery();
Whle(rs.next())
{
System.out.println(rs.getInt(1)++rs.getString(2)+rs.getString(3));
}

While working with jdbc PreparedStatement object we can place


parameters in the sql query just representing input values but we
cannot parameters representing table name, col names and sql
keywords..
Select * from students (valid)

Select * from student where sno>=? (valid)


Select * from student where ?>=? (invalid)
Select * ? student (invalid)
Select * ? ? where ?>=? (invalid)
Note: - using PreparedStatement object we cannot execute DDL queries

having table name, co names as the parameters.


Q: How can we execute static SQL Query by using PreparedStatement
object?
Call ps.execute(-),executexxx(-) methods with agrs on jdbc
preparedStatement object as shown below.
PreparedStatement ps=con.prepareStatement(Select * from student);

ResultSet rs=pr.executeQuery(select * from em);


While(rs.next()) -- executes as static sql query.
{
..
..

}
in the above code select * form student will not be executed but select
* from emp will be executed as static SQL Query.
(Vvi)

What is the difference between simple statement and


PreparedStatement?
Simple statement
1. Deals with static sql query
2. Suitable for executing query for
one time without input values.
3. May raise sql injection problem

4. Makes database engine to compile


sql query with input.
5. Not suitable for date value
insertion.
6. Not suitable for large object
insertion (files)
7. Improves network traffic b/t java

app and database s/w(degrades


the performance)
8. Using one statement object we
can send and execute multiple sql
queries.
9. We need to convert input values

PreparedStatement
1. Deals with pre-compiled sql
query (dynamic query)
2. Suitable for executing query for
multiple times either with same

or different input values.

3. Does not raise sql injection


problem.
4. Makes database engine to
compile without inputs.
5. Suitable for date value insertion
6. Suitable

7. Reduces n/w traffic b/t java app


and database s/w and improves
performance
8. For every sql query we need to
separate PreparedStatement
object.

of query according to sql syntax.

9. Conversion is not required.

Why simple Statement object raises sql injection problem and why sam
problem does not raise in PrepasredStatement.
Simple Statement obj makes the DB engine of Database software to
compile sql query with input values, so the special sql instruction (like
--) that are given along with input values participate in query

compilation, due to the sql query behavior will be changed during


execution because of those special sql instructions (--) this is nothing
but sql injection problem
PreparedStatement object makes the Database Engine of Database
s/w to compile sql query without input values and input values
will be set to query after the compilation of query and before the

execution of the query, so he special sql instruction (like --) that


are given along with the given values does not participate in
query compilation, Due to this they cannot change query
behavior in the execution of query. This indicates NOA=sql
injection problem.
MySQL

TYPE: Database Software


Version: 5.5
Vendor: DevX/sun Microsystem/Oracle Corporation
Open Source
Port no: 3306

Default user-name: root


Password : root (will be chosen during the installation)
Download: www.oracle.com , www.mysql.com
Allow to create logical DBs.
procedure to create logical database having DB table with

records.
Step-1) Launch mysql prog
Start mysql mysql 5.5 command line client
Password (root) which is choosen during installation
Setp2) create Logical DB NTDb1

Mysql> Create database NtDB1;


Step-3) create database table student in NtDb
|no int
|sname varchar
|sadd varchar
Connect NtDb5

Create table student (sno int(5),sname, varchar(20) ,sad


varchar(20))
Insert into student values(111,ramesh,hyd);
Commit.
DevX supplied type4 mechanism based jdbc driver for mysql is

called Connector/j jdbc driver and This driver details are


Driver class name: org.gjt.mm.mysql. Driver(0r)
com.mysql.jdbc.Driver
url: jdbc:mysql:///<Logical DB) (for Local MySql DB s/w)
(or)
Jdbc:mysql://<hostname>:<portno>/<Logical DB>

(protocol)

(for Remote MySQL DB software)

Jar file : Mysql-connector-java-5.1.6.jar


(should be arranged separately)
Example App1) place mysql-connector-java-5.6.jar file or build path

2) Develop the application as shown below.


In Real time programmers /sql developers use GUI DB tools to
perform DB operations like Toad for oracle, Toad for MySQL,
SQLYOG for MySQL, MySQL Front and etc ( separate
installation)

Procedure to use SQLY0G for MySQL logical DB having DB table


with records.
Launch sqlyogcontinuenew (con1)host
address(localhost)Username-root password rootconnect
right click on root crate database (NtDb6)[name of logical

database]createNtDb6(right click)create table


Field name

Datatype

len

Pid

Int

right click on table insert record

Assignment
Develop jdbc app that transfers the record from oracle db table to
my sql table.

Working with date value

2015-03-19

While developing various apps we need to insert DOB, DOJ,


DOMarriage, Bill Date, Expiry date Purchase Date and etc
values Database table along with other values.

Inserting date values as string values in DB table cols is not


recommended because we cannot compare two values and
we cannot subtract one date values from another date values.
It always recommended to insert date values in Date data

type columns of DB table.


Different database s/w support different patterns of date
values.
Oracle: dd-MMM-yy (10-OCT-80)
Mysql: yyyy-MM-dd (1980-10-20)

If we use simple statement object to insert date values we


must place date value in the query in the pattern which is
supported by DB s/w.
If we use PreparedStatement object to insert date value, we
need to give java.sql.Date class object to jdbc driver through

SQL Query and driver inserts date value in dB table in pattern


that is supported by underlying database s/w.
java.util.Date is the super class of java.sql.Date class and it
cannot be used to perform Database operations.
java.sql.Date can be used to perform DB operations.
If you set java.sql.Date class object to jdbc driver representing

date value then jdbc driver inserts the date value in the
pattern it supported by underlying database s/w.
Example application to retrieve different date pattern value and insert
them in database table.
Refer app-10
Person_tab(in oracle)

Ask data of birth from end user and calculate his age.
To retrieve date values from DB table we can use either
Simple Statement object or PreparedStatement object.
To retrieve Date values form jdbc ResultSet object we can use
rs.getDate(-) method.

TO convert java.util.Date class object to String date value use


format.

(1)

App executes select query using simple Statement or


PreparedStatement object and get ResultSet object having Date
values in the form of java.sql.Date class obj.

(2)

Application retrieves java.sql.Date class object to java.util.Date


class object.

(3)

Application Converts java.sql.Date class objects to java.util.Date


class object.

(4)

Application uses format(-) of SimpleDateFormat Date class to


convert java.util.Date class object to String date values.

(5)

App gives this date value to end user.

For above diagram based application refer


If u use rs.getString() method to retrieve date value display in
yyyy-MM-dd pattern.
If you use rs.getDate() method to retrieve value there is possibility

of displaying date value in the pattern that we need.


parse() method of SimpleDateFormat class converts given String
date values ot java.util.Date class object.
format(-) of SimpleDateFormat class convers given java.util.Date
class obj to string date value.
//Agecal.p

import java.util.*;
public class AgeCalApp
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);


System.out.println("Enter DOB(dd-mm-yyyy)");
String dob=sc.next();
//convert string date value into java.util.Date class object.
SimpleDateFormat sdf1=new SimpleDateFormat("dd-MM-yyyy");
Date udob=sdf1.parse(dob);

//get Sys date


Date sysdate =new Date();
//calc age
long ms=(sysdate.getTime()-dob.getTime());
//long ms=System.currentTimeMillis()-udob.getTime();

float age=(float)ms/(1000.0f*60*60*24*365);
System.out.println("Age" +age);
}
}
Q: - Write a jdbc application to copy records from students
records form MySQL to student table of oracle.

Here to get all records mysql student table we need to execute


select *form Student only for time without any input values ,
for this we need to use SimpleStatement object.
To insert the above multiple records in student db table of
oracle we need to execute the same insert SQL Query for
multiple time with different values for this we need to use

PreparedStatement object.
In one application we can have multiple jdbc connection
object, Statement objects ,ResultSet objects.

1. Develop jdbc application that uses prepared statement object to


get employee details based on given based nth .
file:///E:/Javaprogramming/Naresh/mysql/swing/TopSal.java
2. Write the jdbc application to place swing frame application to
insert the record .

file:///E:/Javaprogramming/Naresh/mysql/swing/SetFromSwing.java
3. Write a jdbc application to write the records of database table
to text file or html file
package com.nt;

public class MysqlToOracle


{
public static void main(String[] args) throws Exception
{
//register jdbc dirvers
Class.forName("oracle.jdbc.OracleDriver");

Class.forName("com.mysql.jdbc.Driver");
Connection
oracon=DriverManager.getConnection("jdbc:oracle:thin:laocalhost:152
2:orcl","scott","tiger");

Connection
mysqlcon=DriverManager.getConnection("jdbc:mysql:///NtDb6","water",
"water");
//create statement object
Statement st=mysqlcon.createStatement();

PreparedStatement ps=oracon.prepareStatement("insert into student


values(?,?,?)");
//get records from mysql
ResutlSet rs=st.executeQuery("select * from student");
//insert records into oracle db table
while(rs.next())

{
//get each records from mysql db table
int no=rs.getInt(1);
String name=rs.getString(2);
String addrs=rs.getString(3);
//set the above values to qury paames

ps.setInt(,no);
ps.setString(2,name);
sp.setString(3,addrs);
}//while
System.out.println("records are copiied");
rs.close();

ps.();
mysqlconn.close();
myoracon.close();
}
}
select * from (
select empno
, sal
, dense_rank() over (order by sal desc) as rnk
from emp)
where rnk = 5
/
select * from (select empno,ename,sal,row_number() over(order by sal desc
nulls last) rnm
from emp) where rnm<=10

Working with large object: -

2015-03-23

Files are called large object(LOBS). While developing job portal


application, matrimony applications, profile management
application we need to insert or retrieve large objects.
There are two types of large objects.
A) BLOB: image file, audio file, video file and etc.
B) CLOB: Text file, Rich text file, ms word and etc.
All most all DB s/w are giving support for large objects.. having
blob, clob data types support.
We cannot use simple statement to insert large objects in DB table
cols because we cannot place files as the query input values.

We can use PreparedStatement object to insert Large object


because we can set input stream that points to files as query
parameter(?) values.
To set Blob value to query parameter we can use
ps.setBinaryStream(-,-,-) /ps.setBlob(-,-,-) method.
To set clob value to Query parameter we can use
ps.setCharacterStream(-,-,-) /ps.setClob(-,-,-) method.
The above given code is database independent, jdbc driver indecent to
insert large object.
MySql doesnot allow big size images insertion it allow only small
size images insertion where as oracle support both big size and
small size images insertion.

Buffer:Buffer is a temporary memory that holds data for temporary


period . Buffer is also called cache.
We can take byte[], char[], collections as buffers.
While transferring data/content between source file to destination file
without buffer support then we need to copy byte by byte or character
by character. In the process we need to perform more read operation of
source file and more write operation on destination file.
If the above case if we take the support of buffer then we can
deduce the number of read operations on source file and
number of write operation on destination file.

Retrieving large object for this we can either use simple statement
or PreparedStatement object.
To read clob values from ResultSet we can either
rs.getBinaryStram(-) or rs.getBlob(-) method.
To read clob value form ResultSet we can use either
rs.getCharacterStream(-) or rs.getClob(-) method.

For above refer page 30 of photoretrieve.java

2015-03-31
In Real time the application will be converted .exe file in order to
release them to client organizations
These .exe file can be executed in any system even though java is
not available in that system.

All Desktop games that are developed in java will be converted


into .exe file and will be placed in internet network as
downloadable files.
We can convert javas CUI or GUI application into .exe files by
using J2E tool (jar 2 exe tools).
Ex:- Convert GUI java application into an exe file.

1. Prepare jar file having manifest representing the application.


E:\Apps\Demoexe
|AllStmtsTest.java/.class(App17 of page no 37)
|mymanifest.mf
|AllStmtsTest.class
Mymani.mf
Manifest-Version: 1.0
Main-Class: com.nt.AllStmtsTest //press enter

Manifest file contain the description about content that is


added to jar file.
If ask jar file to execute directly the execution begins from the
main class that is specified in manifest file.
E:\Apps\DemoExe> jar cmf mymani.mf NtApp.jar .

c create jar file


m Specify manifest file
f specify jar file name.
2. Download J2E tool (jar 2 exe tool) from internet
http://www.regexlab.com/download/noc/jar2exe/j2e_free.zip
3. Install J2E tool by using the setup file that comes with

j2e_free.zip file
4. Use J2E tool to convert the above NtAp.jar file to an exe file.
Launch jar to exenextbrows jar (e:\app\demoexe\ntapp.jar
Jre version min 1.6 max 1.7
Target system windows

Select windows GUI application nextnext


Select encrypted hid file. next addbrows and select ojdbc14.jar
next nextfinish.(use Ntapp.exe file)
Working with different types JDBC ResultSet

1. NonScrollable ResultSet : Allows to access records only in top to


bottom direction sequentially.
2. Scrollable ResultSet: Allows to access records bi-directionally ,onsequentially directly and randomly . The ResultSet give faster
access to the records.

Inviolable methods on Non-scrollable ResultSet


next()

getXXX()
close()
getRow() to know the current position of cursor/record pointer in
ResultSet.

Inviolable method on Scrollable ResultSet


next()
previous()

getxxx(-)
getRow(-)
close()
afterLast() Moves the cursor to ALR Position
beforeFirst()
first()
last() moves the cursor to last record
isFirst() checks weather cursor is there in first record or not
isLast() Checks weather cursor is there in last records or not
absolute(+/-n)
relative(+/- n)

refreshRow() Refreshes the current records in ResultSet


updatexxx(-)
etc

What is the difference between absolute method and relative method


while working with scrollable ResultSet object.

Absolute () method moves the cursor in ResultSet with respect to


BFR/ALR position . +ve number indicates forward direction with respect
to BFR position. ve number indicates reverse direction with respect to
ALR position.
absolute(3) moves the cursor to 3rd record from the top.
absolute(-2) moves the cursor to 2nd record from the bottom.

relative(-) method moves the cursor in ResultSet with respect


to current position. +ve number indicates forward direction
and ve number indicates reverse direction.
relative(3) Moves the cursor to next 3 records in forward
direction from current position.

relative(-3) moves the cursor in backward direction (before


3 record)s from current position)
write a jdbc application that display the records of Database table
randomly and bi-directionally?
Refer-> application 18 of page 39 and 40
Assignment:Develop scrollable resultset object with preparedStatement support.
By default Every ResultSet is Forward only ResultSet (nothing Non
Scrollable ResultSet). This ResultSet allows us to access records

sequentially in forward direction.


Q :- What happens if we try to move cursor in Scrollable
ResultSet to unavailable Position?

The application throws java.sql.SQLException:ResultSet

Exhusted.
Creating scrollable ResultSet object by using PreparedStatement object.
PreparedStatement ps=con.prepareStatement(select * from
student,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDA
TABLE);
ResultSet rs=ps.executeQuery();
In the above application we need to move cursor in ResultSet
randomly based on the button that are clicked for this we need to
take Scrollable ResultSet object.

Since there is no previous record for first record so we need to


ensure cursor is not already there in first record before we call
rs.previous() method, for this use rs.isFirst() method
Since there is no next record for last record , so we need to ensure
that cursor is not already there in last record before calling

rs.next() method, for this use rs.isLast() method.


Container: Frame
Components: Label (3)
Button (4)
TextField(3)
Layout manager: FlowLayout

Event: ActionEvent

Event Listener: ActionListener


Event Handling : actionPerformed(-);

For above diagram based application refer application -19 of 40.


NetBeans
Type: IDE for java
Version :7.x (jdk 1.5+)
Vendor: Sun Ms(oracle corporation)

Free IDE
To download s/w: www.Oracle.com (or) www.netbeans.org
App 19 by using NetBean IDE
Step-1) create java project in NetBean
Filenew project java java application next(project

name)

finish

Step-2) Add ojdbc14.jar file to the libraries of the project.


Right click on libraries folder Add jar brows in select ojdbc14.jar
Step-3) Add frame to the source packages folder of the project.
Right click on source packages folder JFrame form (classname=scrollframe) and package com.ntfinish.

Step-4) design application through Drag and drop facilities.


(Refer previous diagram)
Setp-5) Register ActionEvents on theses component
Right click on Button event actionActionperform
Step-6) declare the following instance variable in the source code.
public class ScrollFrame extends javax.swing.JFrame

{
Connection con;
PreparedStatement ps;
ResultSet rs.
}

Step-7) Develop user-defined method having logic to crate Scrollable


ResultSet object and call that method from constructor.
public ScrollFrame()
{
initComponents();

makeConnection();
}

public void makeConnection()


{
//register driver
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:orcl","scott","tiger"
);

ps=con.prepareStatement("select * from

Student",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=ps.executeQuery();

}//try

catch (Exception e)
{
}

e.printStackTrace();

}//end of makeConnection method

Step-8) Write following code in JButton1ActionPerformed(-) for first


button.
Try
{

rs.first();
jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)

e.printStackTrace();
}
Step-9) write following code in JButton2ActionPerformed(-) for next
button.

Try
{
if(!rs.isLast())
{
rs.next();
}
rs.first();

jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();

}
Step-10) write following code in JButton3ActionPerformed(-) for
previous button.
Try
{
if(!rs.isFirst())
{
rs.previous();
}
rs.first();
jTextField1.setText(rs.getString(1));

jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();
}

Step-11) write following code in JButton4


ActionPerformed(-) for last button.
Try
{
rs.last();
jTextField1.setText(rs.getString(1));

jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();

Step-12) Run application


Both Simple Statement and PreparedStatement gives support for
Scrollable ResultSet.
All jdbc drivers support Scrollable ResultSet.

A Scrollable ResultSet can also be developed as


a) Sensitive ResultSet
b) Insensitive ResultSet
c) Read only ResultSet
d) Updatable ResultSet
And etc
Q what is the difference between sensitive and insensitive ResultSet?
Ans: - When ResultSet object is representing DB table records if the
modifications done in DB table are reflecting directly to ResultSet object
then it is called Sensitive ResultSet otherwise it is called insensitive
ResultSet.

To create Sensitive ResultSet


Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.C
ONCUR_UPDATABLE);
ResultSet rs=st.executeQuery(select * from student);

To create insensitive ResultSet


Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.
CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery (select * from student);
While developing application that displays live game score, stock

market share values we need to use Sensitive ResultSet object.


For example application on Sensitive ResultSet refers application20 of the page no-43.
Q:- What is the difference between Read only and Updatable
ResultSet?
Ans) using Read-only ResultSet we can perform only read

operation on DB table using Updatable ResultSet we can perform


insert, update, delete, select operations on DB table. While
working with Updatable ResultSet the modifications done in
ResultSet object will be reflected to DB table.
Q:-What is difference between sensitive and Updatable ResultSet?

Ans) if the modifications done in DB table reflect into ResultSet


then it is called as Sensitive ResultSet.
If the modifications done in ResultSet are reflecting to DB table
then it is called as updatable ResultSet.

To create Read only ResultSet


Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_READ_ONLY)
ResultSet rs=st.executeQuery(Select * from student);
To create Updatable ResultSet

Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE)
ResultSet rs=st.executeQuery(Select * from student);
By using Updatable ResultSet we can perform insert,update,delete

operations on DB table without using any SQL Queries.


Example:To insert record
rs.moveToInsertRow(); creates Empty record in ResultSet.
rs.updateInt(1,900);

rs.updateString(2,ravi); |(setting values to


rs.updataString(3,hyd); |empty record)
rs.insertRow();.//inserts record in DB table
To update record

rs.absolute(3);//goes to 3rd record


rs.updateInt(2,ramana); //modifies 2 col values of 3rd record
rs.updateRow();//updates the record.

To delete record

rs.absolute(2);
rs.deleteRow();//deletes 2nd record.
For example application on updatable ResultSet application -21
page no-43.
Type one driver support updatable ResultSet.
The oracle thin, oci drivers support updatable ResultSet only

when * symbol is replaced with column name in the query.


All jdbc driver support Read-only ResultSet irrespective of any
condition.
Updatable ResultSet are not industry standard
1. Bulk non-select operation complex to perform operation

2. Condition based non-select operation is complex to perform.

Metadata: -

2015-04-03

Data about data is called Meta Data. Knowing information about


existing info is called Meta Data.

For programming related metadata activities we use comments,


modifiers annotations and etc.
In jdbc we use Metadata operations to know database s/w, its db
tables its columns and other details.
Metadata operations in jdbc are not given to perform regular DB
persistence operations.

Jdbc Supports 3 types of Meta data operations.


a) Database metadata (To know limitations and capabilities of
underlying DB s/w.)
b) ResultSet metadata ( To know more information about the
database table that is represented by ResultSet)
c) Parameter metadata(To know more information about

parameters that are in queries of PreparedStatement)


DatabaseMetadata
It is given to know the limitations and capabilities of
underlying Database s/w like table name max chars, support
for pl/sql procedures, functions and etc..

DatabaseMetadata object means it is the object of underlying


Jdbc driver supplied java class that implements java.sql.
DatabaseMetadata(I)
To create this object
DatabaseMetadata dbmd=con.getMetaData();

we can call various on this to know more details about


Database s/w.
This DatabaseMetadata is very useful in real time to develop
GUI DB tools like SQL YOG , MySQL front TOAD and etc.
The results DB Metadata will change based on the DB s/w we use
and the jdbc driver we use.

If underlying jdbc driver is not capable of getting certain


information about debase s/w then methods of Metadata
programming returns 0 or null values.
For example app on database metadata refer page no-45,46 app
no-25.
ResultSetMetaData

It is given to know more details DB table whose records are there


in ResultSet.
ResultSetMetaData objet means it is the object of underlying jdbc
driver supplied java class that implements java.sql.
ResultSetMetaData(I).
To create this object

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


ResultSetMetaData rsmd=rs.getMetaData();
Call various methods on it to know more information
about DB Table.
It is very useful in report generation and in the development of

GUI database tools.


We cannot print Db table records having columns names while
working with ResultSet, for this use ResultSet along with
ResultSetMetaData.
Important methods of ResultSetMetaData(i).
getColumnCount()

getColumnLabel(-)gives col name


getColumnTypeName(-)Gives col data type
getColumnDisplaySize(-)
isSigned(-)
and etc..
for example application on ResultSet metadata to print DB record

along with the column name refer app-25 of the page no46,47

ParameterMetaData

2015-04-04

it is given to gather information about parameters(?) that are


there in the SQL Query represented by PreparedStatement object,
CallableStatement obj.

ParamenterMetaData object means it is the object of underlying


jdbc driver supplied java class that implements
java.sql.ParameterMetaData(I).
To create this object.

preparedStatement ps=con.preparedStatement(insert into student


values(?,?,?);
ParameterMetadata pmd=ps.getParameterData();
Important methods
getParameterCount()

getParameterTypeName(-)
getParameterTypeName(-)
siSigned(-)
isNullable(-)
getScale(-)
getDecimal(i)

and etc
Most of jdbc driver including type-1 driver, oracle thin driver, oi
dirver does not support parameterMetaData because they are not
providing any implementation class for this interface.
Page-47 application-26.
Properties files:-

The Text file that maintains the entries as key values pairs is
called text properties file.
Example: DBDetails.properties
#driver=oracle.jdbc.driver.OracleDriver
url=jdbc:odbc:thin:@loacalhost:1522:orcl

user=scott
password=tiger
java.util.Properties class which is a sub class of java.util.Hastable can
load element values from given text properties file.
//locate properties file

FileInputStream fis=new FileInputStream(DBDetails.properties);


//create Properties class object.
Properties p=new Properties();
p.load(fis);

HashTable allows any obj as keys and values of the elements.


Properties class obj allows only string as the keys and valus of the
elements.

Standard slogan of s/w industry is do not har code any values in


application that are changeable in future; it is recommended to
send those values from application outside.
While developing jdbc application it is recommended to send 4
jdbc properties to application from outside the application as

properties file content.


Jdbc properties are driver class, url, DB user, DB pwd.
This property is very useful when we give only class file to clients.
jdbcProj3
|src
|
Collection of related item is called batch or unit of items.
If we send related queries to db s/w separately one by one then
more network round trips are required between java app and DB
s/w instead of that we can place these quetrips between java app
adn ries in a batch and send batch to database s/w for execution.

This is called batch processing or batch updating. This reduces


network round trips between java app and db s/wries
We can place only

2015-04-07
BatchUpdation using Simple Statement object
Step-1) create Statement object
Statement st=con.createStatement();
Step-2) add batch of non-select queries to
statement object.
St.addBatch(insert into student
values(901,raja,hyd));
St.addBatch(delete from student where sno>100);
St.addBatch(update student set sad=vizag where
sno<=50);
Note: - Any number of queries can be added to
batch, but select query should not be added.
Step-3)Execute the Batch

Int res[]=st.executeBatch();

Step-4) summaries the ResultSet


Int sum=0;
For(int i=0;i<res.length;++i)
Sum=sum+res[i];
Sop(no of records that are affected +sum);//get 4
Note:- The queries of batch will not be executed by
applying do everything or nothing principle, i.e one
or other queries execution is failed then also
remaining queries will be executed.

Conclusion:
executeUpdate(-) :for non-select queries execution
executeQuery(-): for select queries.
execute(): for calling pl/sql procedure/functions
executeBatch(): for batch updatation.
For example of batch processing app-30 page-49.
Transaction management
The process of combining related operations into
single unit and executing them by applying do
every thing or nothing principle is called
transaction management(tx)

Batch processing

does not perform tx automatically, we need to


write additional for that.

Tx deals with 3

operations
a) Begn tx
b)

perform operations
..
c) Commit or rollback.

Begn Tx is nothing

but disabling autocommit on DB s/w through


hava app by using con.setAutoCommit(false);

Commiting Tx is

nothing but con.commit() and rollbacking tx is


nothing but con.rollback();
Sample code
//begin tx
Con.setAutoCommit(false);
Statement st=con.createStatement();
St.addBatch(--------);
St.addBatch(--------);
St.addBatch(--------);
Int res[]=st.executeBatch();
//write Tx code
Boolean flage=true;
For(int i=0;i<res.lenght;l++)
{
If(res[i]==0)

{
Flag =false;
Break;
}
}
If(flag==false)
{
Con.rollback();
System.out.println(Tranction (tx is rollback );
}
Else
{
Con.commit();
System.out.println((transaction (tx) is committed);
}
Transfer money operation is the combination of two operations
a) With draw amount from source account

b) Deposit amount from dest account


We need to execute both operation by enabling do everything or
nothing principle, for that use Transaction management support.
For example application jdbc style transaction management to perform
transfer money operation refer page-50 and 51 application 31
PreparedStatement support Batch processing but not with
multiple sql queries because this object will always be confined to
one sql queries, but we can place multiple sets of this query
param value to batch supporting the processing in that process
we can reduce network round trip between java application and
Db s/w towards setting param value to query.
//create PreparedStatement obj
PreparedStatement ps=con.prepareStatement("insert into
student values(?,?,?)");
//add multiple set of query parames to batch
ps.setInt(1,1000);
ps.setString(2,"Raja");
ps.setString(3,"hyd");
ps.addBatch();//1st set of vaues to batch
ps.setInt(2,1000);
ps.setString(2,"Rajesh");
ps.setString(3,"hyd1");
ps.addBatch();//1st set of vaues to batch

//execute batch
int res[]=ps.executeBatch();
boolean equalsIgnoreCase(String anotherString)
Compare this string to another string, ignoring case
considerations.

What is the difference between batch processing by using simple


statement obje or batch processing by using prepared statement
object.
A simple statement based batch processing allow us to add
multiple query to batch whereas PreparedStatement based object
batch processing does not allow to add multiple queries to batch
but allowed to add multiple sets of queries parameters to batch
The latest version of jdbc is 4.x.
For various releases of jdbc api and their features refer page-1,2
& 3 of booklet.
The two important features of jdbc 3.0
a) Save point.
b) Connection pool.

Save point
The final outcome of transaction is either committing results or roll
backing result if u want ot perform both commit or rollback acticity in
a transaction then we need to use save point.
Save point is a point in a transaction up to which we can rollback.
Begin Tx
Operation-1
Operation-2
Save point p1
Operation-3
Operation-4
Rollback to p1
Commit Tx
Here operation-1, operation-2 will committed and operation-3
and operation-4 will be rolledback.
There are two types of save point
1. Named save point (programmer gives name)
2. UnNamed save point(DB s/w gives name internally)
To create Save Point
SavePoint sp=con.setSavePoint(mysp);

Note:- Save point object means it is the object of underlying driver


supplied java classs that impements java.sql.SavePoint(().
To rollback upto save point
Con.rollback(sp);
Let us assume there are two activites in shopping
a. Item booking
b. Item purchase.
Even though item Purchase is failed, the item booking should
be continued for this use save points like this.
Begin Tx
--Book item
--Save point sp1
Purchase item (if failed)
--Rollback to sp1
Commit Tx.
For example application on save point refer page no-53,54
question no-35.
Connection Pool:Working with jdbc connection pool

Connection pool is a factory that contains set of readily available


con objects having following advantages.
a. Gives reusability of con objects.
b. Using minimum connection object we can make max apps to
interact with database s/w
c. Creation, destruction , mainaging con obj will be taken care by
jdbc con pool
Two types of jdbc ocn pools.
a) Client side connection pool
Useful in application that runs as standalone or tow-tire
application without any server support.
b) Server side connection pool
Useful in application that are deployable in servers (web server)
eg: websites

All connection objects in connecton pool represents connectivity


with same databse s/w

Data source obect represents jdbc connection pool. Each


connection pool must be retrieved through DataSource object.
Data source object means it is the object of java class that
implements javax.sql.DataSource(I).
Apache DBCp, c3p0,Oracle Thin Driver supplied connection
pools are client side con pools.
Tomcat, weblogic managed connection pools are server
managed jdbc connection pools.
The oracle thin driver (ojdbc14.jar ) gives
OracleConnectionPoolDataSource class to creae DataSource
obect representing jdbc connection pool. This class implements
javax.sql.DataSourc(I) directly or indirectly.
TO get connection object from jdbc connection pool through
DataSource object use ds.getConnection() method.
For example application oracle thin driver based app-34
How many ways are there to create jdbc connection object?
a) Direct jdbc connection(created by the programmer manually)
Class.forName(..);
Connection
con=DriverManager.getConnection(..,,);
Direct jdbc connection
b) As pooled jdbc con(Collected from the jdbc con pool)
Connection con=ds.getConnection();

Pooled jdbc connection object..


the important feature of jdbc 4.x is autoloading of jdnc driver
class that means ther is no need of placing Class.forName(-) in
jdbc application.
Ojdbc14.jar is given based on jdbc 3.0 so it does not support ther
above fature
Odbc6.jar is given based on jdbc 4.0 so it support above feature.
Ojdbc6.jar file contains java.sql.Driver file in META-INF \servies
folder having driver class name and our applications
automatically takes and load that driver class from that file of jar
file.
Java.sql.Driver
Oracle.jdbc.driver.OracleDriver
Ojdbc14.jar does not contain java.sql.Driver file , so it doesnot
support Auto-loading of jdbc driver.
Example application
----------------------------------------------Step-1) Add odbc6.jar file to classpath or build path
Step-2) Take any jdbc application of oracle thin/oci driver and
execute it with out placing//Class.forName(-);

There are two type of database software


a) Conventional sb s/w
Eg. Ms-acces, oracle, mysql
b) Non- conventional db s/w
Eg. Ms.excel, ms-word, TextFiles (csv, tab files and etc)
These are not originally database software but we can use them as
database software.
In real time conventional database software used as main database
software of the project and non- conventional database software will be
used as supporting database s/w of the project.
Use case:: ICICI bank uses oracle as main database s/w and transfers
every 3 months data to Ms-Excel to taking print outs of accounts
statements.
Use case 2: in mobile apps/games development non-conventional
database software will be used for persistence operations because they
do not occupies much memory.
To interact non-conventional database s/w we generally use type-1
driver with the support of odbc driver because type-4 mechanism driver
are commercial drivers to use ..

note: one physical DB s.w we can have multiple logical


DBS on on per project basis.

Setp-1) create MS-excel work book and work sheet as shown above
E:\apps
|------college.xls
|----sheet1
Step-2)create dsn for ms-excel
Step-3) develop the application

import java.sql.*;
import
public class ExcelTest
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:xlsdsn");//xlsdsn
Statement st=con.createStatement();
//send and sql query
ResultSet rs=st.executeQuery("select * from [Sheet1$]);//sheet1$->
sheet name as table name
//process the result

while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}
int resutl=st.executeUpdate("insert into[sheet1$] values(901,'raja','hyd');
st.close();
rs.close();
con.close();
}
}

Working with text files


The Files that contains formatted data can treated DB table example csv
file, tab file and etc (here we must have common delimiter to separate
the values)

Here FileSystem of a computer acts as physical DB s/w. in that each


folder acts as one logical DB s/w. Each formatted file can be taken as
database table.
E:\
| ----------apps(logical DB)
|------------files1.csv(table1)
|-----------files2.tab(table2)
Procedure to interact with Formatted file from java application(csv file)
Step1) create file1.csv as shown above
Step2) create dsn for Microsoft Text Driver(odbc driver)
Step3)add Microsoft text driver(*.txt,*.csv)
Step4) txtdsnuse current directory select directory E:\aapsok
Step5) develop the application

//textTest.java
import java.sql.*;
public class TextFileAsDatabase
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:txtdsn");//txtdsn--dsn name
//crate staement
Statement st=con.createStatement();
//execute query
ResultSet rs=st.executeQuery("select * from file1.csv");//file1.csv--file
name as database table
//process the result set
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}
rs.close();
st.close();
con.close();
}
}

We can use one statement object to send and execute multiple sql
queries in database s/w one after another.

Postgresql
Type: DB s/w

2015-04-11

Version: 9.x
Vendor:- Enterprise DB

Default logical DB: postgresql


Default username: postgresql
Password: root (should be chosen during installation)
Default port no: 5432
To download s/w: www.postgresql.org
Postgresql-9.0.2-1-windows.exe

In one physical Database s/w we can create multiple logical DBs on one per
project basis.

Procedure to create logical db having DB in postgresql

Start> all>next>postgresql>pc admin>pcadmin3>right click on


postgresql>connect>password=root.
Righ Click on databases>new Database>NtDb2>ok>expand
NtDb2>schemas>public >tables>New Table>asking me table
name=Product>columns>
Pid

integer

Pname Character varying


Price
>OK

double precision

>expand tables right click on product.>scripts>insert script>replace ? with


value.
Insert into product (pid,pname,price)values(101,table,9000);

Type4 mechanism based jdbc driver for postgresql is technically called as


postgresql thin driver. The driver details are:
Driver class name: org.postgresql.Driver
jdbc: postgresql protocol
Jdbc url: jdbc: postgresql:<logicalDatabase>
Jar file: postgresql-8.4-701.jdbc4.jar
www.postresql.org
example application that interact with postgresql database s/w
step-1) add postgresql-8.4-701.jdbc4.jar file to classpath to buildpath.
import java.sql.*;

public class PostgreSQLApp


{

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


{

Class.forName("org.postgresql.Driver");
//establised the connection
Connection

con=DriverManager.getConnection("jdbc:postgresql:NtDB2","postresql",root");
//create statement object

Statement st=con.createStatement();
//execute query

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


//process the result
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}

con.close();

Right click on project>buildpath>add external achieves


Step-2) develop application using above details.

Working with MS-access


The companies who has already purchases MS office for their office work prefer
using MS-access as database s/w in projects.
The type -4 mechanism drivers of MS-access is commercial so we use type-1
jdbc driver along with odbc driver to interact with MS-access.
In MS-Access each .accdb or .mdb file is called as on logical DB. We can
create any no.of Logical DBs in MS-Access.

Procedure to create Logical DB having table in MS-access.


start>all prog>ms-office>ms-access>officeButton>New>College>e:\apps>create
Right click on table1> design view>Table name-student>chose col name>
Sno

number

Sname

text

Sad

text

Ctrl+w> enter record


101

ramesh

hyd

102

raja

vizag

Example application to interact with MS-Access using type-1 driver: Step-1) create dsn for Ms-Access driver.
Launch odbcas32.exeuser dsn add

accdbaccdsnselect

e:\app\college.accdbok
Step-2) developed java application with type-1 driver.
//AccessTest.java

import java.sql.*;

public class AccessTest


{

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


{

//register driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection

con=DriverManager.getConnection("jdbc:odbc:accdsn");
}

//accdsn

RowSet
To send java object over the network the object must be taken as
serializable object . For this the class of object must implement
java.io.Serilizable(I).
Java Bean is java class that following standards.
a) Class must be public
b) Class must implement java.io.Serializable
c) Class should have private properties(members)
d) Class should have 0-parameter constructor
e) Every property should have setter and getter methods
public class Student implement Serializable
{
//poperty
private sno;
public student()
{}
//setters and getters
public void setSno()
{
this.sno=sno;
}
public int getSno()

1.
2.
3.
4.
5.

{
return sno;
}
}//end class
Jdbc ResultSet are not srilizable object so we can not send them over
the n/w.
ResultSet can not created through Bean style programming(settes and
getters)
To overcome these problem use jdbc 2.0 feature Rowset. The benefits are
a) Most of the Rowsets are serilizables.
b) Can be created easily through bean style programming.
Resultset object are connected object that means to process ResultSet
our application should maintain connectivity with database s/w even
after crating the ResultSet object.
We can see Row Set as connected object or disconnected object.
Disconnected object means we need not to have connection with DB
s/w to process Row Set once the Rowset has been created.
Rowset object means it is the object of driver supplied java class that
implements javax.sql.RowSet(I). This is sub interface of
java.sql.ResultSet(I).
There are five type of Rowsets.
Jdbc RowSet (Connected RowSet)
CachedRowSet (disconnected RowSet)
WebRowSet (disconnected RowSet)
Join RowSet (disconnected RowSetora)
Filtered RowSet (disconnected RowSet)


Oracle corp has given 5 classes supporting these 5 RowSets
1. OracleJDBCRowSet
2. OracleCacheRowSet
3. OracleWebRowSet
oracle.jdbc.RowSet packgae
4. OracleJointRowSet
5. OracleFilterdRowSet
Jdbc RowSet
It is a connected Rowset.
Modification done in the RowSet will be reflected to table directly
without any special method.
It is more like regular jdbc ResultSet object that allows bean style
programming.
This RowSet is not a serializable object.
For example application -28 page -48
cachedRowSet
It is a disconnected RowSet
It acts as a Buffer/cache after getting records from DB table RowSet.
We can manipulate/process this RowSet even though connectivity with
DB s/w is not there, but we should call acceptchanges() method
explicitly to refect the modifications back to DB table.
Except JDBCRowSet all RowSet are serializable objects.
For example application -27 of page no-47.

While developing pda (personal digital app) for lic agent we should we in
position to process the data without database connectivity, we use
cache RowSet.
crowset.setReaOnly(false);
//insert record
crowset.setReadOnly(false);
crowset.moveToInsertRow();//empty row in RowSet
crowset.updateInt(1,001);
crowset.insertRow();//inserts record
crowset.acceptChanges();//connects back to DB
//delete record
crowset.absolute(2);
crowset.deleteRow();
crowset.acceptChanges();
//update record
crowset.absolute(3);//points to 3 row in RowSet
crowset.updateString(2,'yyy');
crowset.updateRow();
crowset.acceptChanges();
WebRowSet
It is same as CachedRowSet but allows renders output S mcl (db table
records) and also inputs as xml.
In web environment if we want to Db table records to xml file content
then use webRowSet.
In webServices two dissimilar application talk with each other by passing
data in the form of xml. To get that data from dB table and to convert
into xml use webRowSets.
For example appl ref ap-29 page-48