ei = 3
NC NARESH —
Opp Satyam Theatre, Ameerpet, Hyderabad -16 TECHNO logies
SGN oe
Ph: 040-23746666, 23734842 Cell: 9000994007 / 08
Branches : CHENNAI PH:044.6555 5557/58 VIJAYAWADA PH:0866-6576789 NELLORE PH:81068 22902
info@nareshit.com _) www.nareshit.com nareshit {4 nareshitechAdvanced java
By
Mr. NatarajNaresh / Technologies JDBC
JDBC
Java Database Connectivity ov in short JDBCis a technology
manipulate data stored into the database.
By Mr. Nataraj
< enables the java program to
DBC is Java application programming interface that allows the Java programmers to access
database management system from Java code. It was developed by JavaSoft, a subsidiary of
‘Sun Microsystems.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs
to execute SQL statements. It is an application programming interface that defines how a java
programmer can access the database in tabular format from Java code using a set of standard
interfaces and classes written in the Java programming language
JDBC has been developed under the Java Community Process that allows multiple implementations
to exist and be used by the same application. JDBC provides methods for querying and updating
the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the
correct Java packages and drivers and registering them with the JDBC Driver Manager that is used
as a connection factory for creating JDBC connections which supports cresting and executing
statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the JDBC
architecture,
Generally all Relational Database Management System supports SQL and we all know that Java is
platform independent, so JDBC makes it possible to write a single database application that can
run on different platforms and interact with different Database Management Systems
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for
accessing and managing database, but the difference is that JDBC is designed specifically for Java
programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1, Ithelps us to connect to a data source, like a database.
2. Ithelps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to.
your query. ~
JDBC Versions
The JDBC 1.0 API.
The JDBC 1.2 API.
The JDBC 2.0 Optional Package API.
The JDBC 2.1 core API
The JDBC 3.0 API.
The JDBC 4.0 API
peer
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph 040-23746666, wuvw.fo.com/nareshitNaresh / Technologies JDBC * By Mr. Nataraj
Ee
Features of ID8C 1.0 API
The JDBC 1.0 API was the first officially JDBC API launched consists of the following java classes and
interfaces that you can open connections to particular databases
This version includes a completely redesigned administration console with an enhanced graphical
interface to manage ad monitor distributed virtual databases.
Features of JDBC 1.2 APL
1. Itsupports Updatabale ResultSets.
2. The DatabaseMetaData code has been refactored to provide more transparency with
regard to the underlying database engine.
3, New pass through schedulers for increased performance
Features of The JDBC 2.0 Optional Pacakage API
The use of DataSource interface for making a connection.
{Use of INDI to specify and obtain database connections.
It allows us to use Pooled connections, that is we can reuse the connections.
In this version the distrbuted transactions is possible.
It provides a way of handling and passing data using Rowset technology.
yPeNe
Features of the JDBC 2.1 core API.
1. Scroll forward and backward in a result set or has the ability to move to a specific row.
2. Instead of using SAL commands, we can make updates to a database tables using methods
in the Java programming language
3. Wé can use multiple SQL statements in a a database as a unit, or batch.
4, It uses the SQL3 datatypes a5 column values. SQL3 types are Blob, Clob, Array, Structured
type, Ref.
5, Increased support for storing persistent objects in the java programming language.
6. Supports for time zones in Date, Time, and Timestamp values.
7. Full precision for java.math.BigDecimal values.
Features of SDBC 3.0 API
4° Reusability of prepared statements by connection pools.
2. In this version there is number of properties defined for the ConnectionPoolDataSource.
These properties can be used to describe how the PooledConnection objects created by
DataSource objects should be pooled,
3. Anew concept has been added to this APIs of savepoints.
4. Retrieval of parameter metadata.
It has added a means of retrieving values from columns con
values.
Added a new data type i.e. java.sql. BOOLEAN.
Passing parameters to CallableStatement.
The data in the Blob and Clob can‘be altered.
DatabaseMetalata API has been added.
ing automatically generated
pane
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd Ph: 040-23746558, wwwfo.com/nareshit 2:
‘mennancsnsceenennartsnannaesifany sisi ihstnnanthiaeaesaets ONIN ete naomi cnNaresh i Technologies
JDBC
By Mr. Nataraj
————— ees
Features of JDBC 4.0:
1. Auto- loading of IOBC driver class,
Connection inanagement enhancements.
Support far Rowld SAL type.
SQL exception handling enhar:cements.
oy Run
SQL XML support
JDBC 3.0 & JDBC 4.0
JDBC 3.0
DataSet implementation of SQI using Annotations.
JDBC 4.0
Features:
= Reusabilty of prepared statements by
connection pools.
= In this version there is number of properties
defined for the ConnectionPooiDataSource. These
properties can be used to describe how the
PooledConnection objects created by DataSource
objects should be pooled.
| - Anew concept has been added to this API is of
savepoints: One of the useful new features is
transactional savepoints. With JDBC 3.0, the
| transactional model is now more flexible.
~ Retrieval of parameter metadata
- It has added a means of retrieving values from
columns containing automatically generated
values.
- Added a new data type i.e. java.sql. BOOLEAN.
- Passing parameters to CallableStatement.
- The data in the Blob and Clob can be altered:
JDBC 3.0 introduces a standard mechanism for
updating BLOB and CLOB data.
~ DatabaseMetaData API has been added.
- It allows stored procedure parameters to be
called by name.
Features:
~ Auto- loading of JDBC driver class: In JDBC
4 invoking the getConnection() on
| DriverManager will automatically load a
driver.
- Connection management enhancements
{In jdbc it may happen that a Connection is
lying idle or not closed in a pool, then it
becomes stale over time. This will lead to
the connection pool run out of resource
due to stale connection
~ Support for Rowld data type: JDBC
introduces support for ROWID, a data type
that had been in use in database products
even before it became part of the SQL.
- SQL exception handling enhancements:
JDBC 4 addresses the error handling
beautifully. As databases are often
remotely accessible resources, problems
| such as network failures is common and it
| can cause exceptions when executing a
database operation. SQL statements can
also cause exceptions. Prior to JDBC 4, most
JDBC operations generated a simple
SQLException
~ SQL XML support.
- DataSet implementation of SQL using
Annotations: The JDBC 4.0 specification
leverages annotations to allow developers
to associate a SQL query with a Java class
without a need to write alot of codeto *
achieve this association.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwnw.fo.com/nareshitNaresh i Technologies JDBC By Mr, Nataraj
‘An important part of every business is to keep records. We need to keep records of our customers,
the employees of our company, the emails etc. To keep all the data indivually is quite difficult and
hectic job, because whenever if we need the record of a particular customer or an employee we
need to search manually. It takes lot of time and still not reliable. Here comes the concept of
databases.
What is database?
A database is an organized collection of information. A simple example of a database are like your
telephone directory, recipe book ete.
A Relational model is the basis for any relational database management system (RDBMS). A
relational model has mainly three components:
1. Acollection of objects or relations,.
2. Operators that act on the objects or relations.
3, Dataiintegrity methods.
To design a database we need three things:
1. Table
2: Rows
3. Columns.
A table is one of the most important ingredient to design the database. It is also known as a
relation, is’a-two dimensional structure used to ‘hold related information. A database consists of
‘one or more tables.
A table contains raws : Rows is a collection of instance of one thing, such as the information of one
employee.
A table contains the columns: Columns cantains all the information of a single type. Each column in
a table is a category of information referred to as a field.
One item of data, such as single phone number of a person is called as a Data Value.
ACID Properti
ACID properties are one of the important concept for databases. ACID stands for Atomicity,
Consistency, Isolation, and Durabilisy. These properties of a DBMS allow safe sharing of data.
Without these properties the inaccuracy in the data will be huge. With the help of the ACID
properties the accuracy can be maintained.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www. fb.com/nareshit
i
!
i
|
|Naresh / Technologies JDBC By Mr. Nataraj
Normalization:
Normalization is a design technique which helps the to design the relational databases.
Normalization is essentially a two step process that puts data into tabular form by removing
redundant data from the relational tables. A basic goal of normalization is to create a set of
relational tables that are free of redundant data and the data should be consistent. Normalization
has been divided into following forms.
1. First Nor
coiui
al Form: A relational table, by definition are in first normal form. All values of the
ins are atomic. It means that it contains no repeating values.
2. Arelation| table is in second normal form if it is in INF and every non- key column is fully
dependent upon the primary Key.
3. Avrelational table is in third normal form (3NF} if it is already in 2NF and every non- key
column is non transitively dependent upon its primary key. The advantage of having table in
3NF is that it eliminates redundant data which in turn saves space and reduces
manipulation anomalies.
Understanding Common SQL statements
The commonly used SOL statements are:
1): Select
2): Insert
3): Update
4); Delete .
SQL Select statement:
The SELECT statement is used to select data from a table.
Syntax: Select column_names FROM table_name;
The result from a SQL query is stored in a result test. The SELECT statement has mainly three
clauses.
4) Select
2) From
3) Where
The Select specifies the table columns that are retrieved. The From clause tells from where the
tables has been accessed. The Where clause specifies which tables are used. The Where clause is
optional, if not used then all the table rows will be selected.
We can see that we have used semicolon at the end of the select statement. It is used to separate
each SQL statement in database systems which helps us to execute more than one SQL statement
in the same call to the server.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.cont/nareshitNaresh i Technologies JOBE By Mr. Nataraj
‘SQL INSERT Statement:
This statement allows you to insert a single or multiple records into the database. We can specify
the name of the column in which we want to insert the data
Syntax: Insert into table_name values (valuet, value2..};
The Insert statement has mainly three clauses.
1) Insert: it specifies witich table column has to be inserted in the table.
2), Into: It tells in which the data will be stored.
3) Values: In this we insert the values we have to insert.
We can also specify the columns for which we want to insert data.
The UPDATE Statement:
The Update statement is used to modify the data in the table. Whenever we want to update or
delete a row then we use the Update statement.
The syntax is :
UPDATE table_name Set colunm_name = new_value WHERE column_name = some_name;
‘The Update statement has mainly three clauses.
1) UPDATE: It specifies which table column has to be updated.
2) Set: It sets the column in which the data has to be updated.
3) Where: It tells which tables are used.
‘SQL DELETE Statement:
This delete statement is used to delete rows in a table.
Systax:
DELETE FROM table_name WHERE column_name = some_name;
The Delete statement has following clauses.
1) Delete: It specifies which table column has to be deleted.
2) From: It tells from where the Table has been accessed.
3) Where: tt tells which tables are used.
Introduction to java.sal package
This package provides the APIs for accessing and processing data which is stored in the database
especially relational database by using the java programming language. It includes a framework
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 6:Naresh / Technologies 1BC By Mr. Natarai
where we different drivers can be installed dynamicalty to access different databases especi=!"
relational databases.
This java.sq! package contains API for the following
1 Making a connection with a database with the help of DriverManager class
© DriveriManager class: It helps co make a connection with the driver.
* SQLPermission class: It provides a permission when the code is running within a Security
Manager, such as an Applet. It attempts to set sip.2 Jogging.stream through the
DriverManager class.
* Driver interface : This interface is mainly used by the DriverManager class for registering
and connecting drivers based on JDBC technology.
* DriverPropertyinfo class : This class is generally not used by the general user.
2. Sending SQL Parameters to a database:
* Statement interface: It is used to send basic SQL statements,
* PreparedStatement interface: It is used to send prepared statements or derived SQL
statements from the Statement object
* CallableStatement interface : This interface is used to call database stored procedures.
© Connection interface : It provides methods for creating statements and managing their
connections and properties.
‘© Savepoint: It helps to make the savepoints in a transaction.
3. Updating and retrieving the results of a que
* ResultSet interface: This object maintains a cursor pointing to its current row of data.
The cursor is initially positioned before the first row. The next method of the resultset
interface moves the cursor to the next row and it will return false if there are no more
rows in the ResultSet object. By default ResultSet object is not updatable and has a
cursor that moves forward only.
4, Providing Standard mappings for SQL types to classes and interfaces in Java Programming
language. :
* Array interface: It provides the mapping for SQL Array.
Blob interface : It provides the mapping for SQL Blob.
Clob interface: It provides the mapping for SQL Clob.
Date class: It provides the mapping for SQL Date.
Ref interface: It provides the mapping for SQL Ref.
Struct interface: It provides the mapping for SOL Struct.
Time class: It provides the mapping for SQL. Time.
Timestamp: It provides the mapping for SQL Timestamp.
Types: It provides the mapping for SOL types.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
5. Metadata
* DatabaseMetaData interface: It keeps the data about the data. It provides information
about the database.
© ResultSetMetaData: It gives the information about the columns of a ResultSet object.
© ParameterMetaData: It gives the information about the parameters to the
PreparedStatement commands.
6. Exceptions
© SQLException: It is thrown by the mehads whenever there is a problem while accessing the
data or any other things.
‘© SQLWarning: This exception is thrown to indicate the warning.
¢ BatchUpdateException: This exception is thrown to indicate that all commands in a batch
update are not executed successfully.
‘+ DataTruncation: It is thrown to indicate that the data may have been truncated.
7. Custom mapping an SQL user- defined type (UDT) to a class in the java programming language.
‘© SQLData interface: It gives the mapping of a UDT to an intance of this class.
‘© SQUnput interface: It gives the methods for reading UDT attributes from a stream.
* . SQLOutput: It gives the metheds for writing UDT attributes back to a stream.
DriverManager Class
The JDBC DriverManager
The JDBC Driver Manager is a very important class that defines objects which connect Java
applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. t's
very simple and small that is used to provide a means of managing the different types of JDBC
database driver running on an application. The main responsibility of JDBC database driver is to
load all the drivers found in the system
properly as well as to select the most appropriate driver from opening a connection to a database.
The Driver Manager also helps to select the most appropriate driver from the previously loaded
drivers when a new open database is connected.
The DriverManager class works between the user and the drivers. The task of the DriverManager
class is to keep track of the drivers that are available and handles establishing a connection
between a database and the appropriate driver. It even keeps track of the driver login time limits
and printing of log and tracing messages. This class is mainly useful for the simple application, the
most frequently used method of this class is DriverManager.getConnetion(). We can know by the
name of the method that this method establishes a connection to a database.
The DriverManager class maintains the list of the Driver classes. Each driver has to be get
registered in the DriverManager class by calling the method DriverManager.registerDriver()
By calling the Class.forName() method the driver class get automatically loaded. The driver is
—— ee ee
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph; 040-23746666, www.fo.com/nareshit 2:
ieee smcesaniasecunianstitnieeidenessntstitsnemnn antennae
\\ DataSource has a set of properties that identify and desc
Naresh j Technologies JDBC By Mr. Nataraj
————>>>_———————
loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager
about themselves automatically when their driver implementation class get loads.
This class has many methods. Some of the commonly used methods are given below:
1, deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the
DriverManager class. ’
2. registerDriver(Driver driver) : It registers the driver with the DriverManager class.
getConnection(String url) : It tries to establish the connection to a given database URL.
4. -getConnection(String url, Sting user, String.password) +t tries to establish the connection
toa given database URL.
5. getConnection(String url, Properties info) : It tries to establish the connection to @ given
database URI.
6. getDriver(String url): It attempts to locate the driver by the given string.
7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the
DriverManager class.
Understanding Data Source
4The JDBC API provides the DataSource interface as an alternative to the DriverManager for
establishing the connection. A DataSource object is the representation of database or the data
source in the Java. programming language. DataSouce object is mostly preferred over the
DriverManager for establishing a connection to the database.
DataSource object can be thought as a factory for making connections to the particular database
that the DataSource instance represents.
e the real world data source that it
represents. The properties include information about the location of the database server, the
network protocol use to communicate with the server the name of the database and so on.
DataSource object works with JNDI (lava Naming and Directory interface) naming service so
application can use the JNDI API to access the DataSource object.
In short we can say that the DataSource interface is implemented to provide three kinds of
connections:
1), Basic DataSource class
_____ This class is provided by the driver vendor. It is used for portability and easy maintence.
2). Te provide connection pooling.
It is provided by the application server vendor or driver vendor. It works with .
ConnectionPoo!DataSource class provided by a driver vendor. Its advantage is portability, easy
maintenence and increased performance.
eee
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
3). To provide distributed transactions
This class works with an XADataSource class, which is provided by the driver vendor. Its
advantages are easy maintenence, portability and ability to participate in distributed transactions.
Understanding Connection Object
A Connection object represents a connection with a database. When we connect to a
database by’ using connection method, we create a Connection Object, which represents ‘the
connection to the database..An.application-may-have-one-or more than -one-connections with a
single database or many connections with the different databases also.
We can use the Connectian object for the following things:
1. It creates the Statement, PreparedStatement and CallableStatement objects for executing
the SQL statements.
2, Ithelps us to Commit or roll back a JDBC transaction.
3. If you want to know about the database or data source to which you are connected then
the Connection object gathers information about the database or data source by the use of
DatabaseMetaData.
4, It helps us to close the data source. The Connection.isClosed() method returns true only if
the Connection.clase() has been called. This method is used to close all the connection.
Firstly we need to to establish the connection with the database. This is done by using the method
Drivertvianager.getConnection(). This method takes a string containing a URL. The DriverManager
class, attempts to locate a driver that can connect to the database represented by the string URL.
Whenever the getConnection() method is called the DriverManager class checks the list of all
registered Driver classes that can connect to the database specified in the URL.
Syntax:
String url = "jdbc: odbc: makeConnection";
Connection con = DriverManager.getConnection(url,"userlD",""password");
Choosing a DB Driver:
The type of driver depends on quite a few parameters : whether the application is internet based,
whether it needs to support heterogeneous databases, the number of concurrent users, a1d so on.
JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation
with increasingly higher levels of platform indolence, performance, and deployment
administration.:
JDBC driver types .
JDBC drivers are divided into four types or levels. Each type defines-a JDBC driver implementation
with increasingly higher levels of platform independence, performance, and deployment
administration, The four types are:
EE
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh / Technologies JoBc By Rie, ataraj
© Type 1: JDBC-ODBC Bridge
Type 2: Native-API/partly
© Type 3: Net-protocol/all-Java
«Type 4: Native-protocol/al
Type 1: JDBC-ODBC Bridge
The type 1 driver, IDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase
Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in
“many cases, the client database.code, must.be.present.on the-dient. machine. Figure 1 shows a
typical S0BC-ODBC Bridge environment.
Client macl
BDBC-ODBC balige
Y
VowerDB liney
Figure 1. Type 1: JDBC-ODBC Bridge
Pros
The !DBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are
already available. Type 1 drivers may be useful for those companies that have an ODBC driver
already installed on client machines. .
Cons
+ The performance is degraded since the JDBC call goes through the bridge to the ODBC
driver, then to the native database connectivity interface. The result comes back through
the reverse process. Considering the performance issue, type 1 drivers may not be suitable
for large-scale applications.
+ The ODBC driver and native connectivity interface must already be installed on the client
machine. Thus any advantage of using Sava applets in an intranet environment is lost, since
the deployment problems of traditional applications remain.
Type 2: Native-API/partly Java driver
JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific
calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates
directly with the database server; therefore it requires that some binary code be present on the
client machine.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www. fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
Client machine Server mathine
Figure, Type 2: Native-API/partly fava driver
Pros
Type 2 drivers typically offer significantly better performance than the JDBC-ODBC Bridge.
Cons ' 7
The vendor database library needs to be loaded on each client machine. Consequently, type 2
drivers cannot be used for the Internet. Type 2 drivers show ower performance than type 3 and
type 4 drivers,
Type
Net- tocol/all-Java driver
JDBC driver type 3 ~- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the
JDBC database requests are passed through the network to the middle-tier server. The middletier
server then translates the request (directly or indirectly) to the database-specific native-
connectivity interface.to further the request to the database server. If the middle-tier server is
written in Java, it can use a type 1 or type 2 JDBC driver to do this.
‘Clisntmmechine|
fret gabtcel pare Jara]
‘iver
Figure 3. Type 3: Net-protocol/all-Java driver
Pros
The net:protocol/all-Java driver is server-based, so there is no need for any vendor database library
to be present on client machines. Further, there are many opportunities to optimize portability,
performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC
driver very small and fast to load. Additionally, a type 3 driver typically provides support for
features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing,
——
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
Cons
Type 3 drivers require database-specific coding to be done in the middle tier. Additionally,
traversing the recordset may take longer, since the data comes through the backend server.
‘Type 4: Native-protocol/all-Java driver
The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific
database management system {OBMS) protocol so that client applications can communicate
directly with the database server. Level 4 drivers are completely implemented in Java to achieve
platform independence and eliminate deployment administration issues.
Glen machine
ave pobeal
“re Dobe
Figure 4. Type 4: Native-protocol/all-Java driver
Pros
Since type 4 JDBC drivers don't have to translate database requests to ODBC or a native
connectivity interface or to pass the request on to another server, performance is typically quite
good. Moreover, the native-protocol/all-Java driver boasts better performance than types 1 and 2.
Also; there's no need to install special software on the client or server. Further, these drivers can be
downloaded dynamically.
Cons
With type 4 drivers, the user needs a different driver for each database.
Choosing right Driver
Here we will walk through initially about the types of drivers, availability of drivers, use of drivers in
different situations, and then we will discuss about which driver suits your application best.
Driver is the key player in a JDBC application, it acts as a mediator between Java application and
database. It implements {OBC API interfaces for a database, for example Oracle driver for oracle
database, Sybase driver for Sybase database. It maps Java language to database specific language
including sat.
JDBC defines four types of drivers to work with. Depending on your requirement you can choose
one among them.Naresh i Technologies JDBC By Mr. Nataraj
eS
Here is a brief description of each type of driver :
Type of driver fier [Driver mechanism Description
[This driver converts JDBC calls to ODBC calls
hrough JOBC-ODBC Bridge driver which in turn]
e et means converts to database calls. Client requires ODBC
ibraries.
Ithis driver converts JDBC calls to database specif
b Irwo [Native API Partly - Java, tive calls, Client requires database specifi
ieriver a
libraries,
[This driver passes calls to proxy server througtl
t
I Ihre )ORC- Net -liJave driver (MtOTk protocol which in turn converts
|database calls and passes through database specifi
ratocal, Client doesn't require any driver.
INative protocol - All - JavaiThis driver directly calls database. Client doesn't
driver + require any driver.
4 Two
Obviously the choice of choosing a driver depends on availability of driver. and requirement.
Generally all the databases support their own drivers or from third party vendors, (f you don't have
driver for your database, JDBC-ODBC driver is the only choice because all most all the vendors
support ODBC. If you have tiered requirement ( two tier or three tier) for your application, then you
can filter down your choices, for example if your application is three tiered, then you can go for
Type three driver between client and proxy server shown below. If you want to connect to
database fram java applet, then you have to use Type four driver because it is only the driver which
supports that feature. This figure shows the overall picture of drivers from tiered perspective.
Type 12 Drives
Database
Type 1.24 Drivers
This figure illustrates the drivers that can be used for two tiered and three tiered applications. For
both two and three tiered applications, you can filter down easily to Type three driver but you can
use Type one, two and four drivers for both tiered applications. To be more precise, for java
applications( non-applet) you can use Type one, two or four driver. Here is exactly where you may
make a mistake by choosing a driver without taking performance into consideration, Let us took at
that perspective in the following section.
Type 3 & 4 drivers are faster than other drivers because Type 3 gives facility for optimization
techniques provided by application server such as connection pooling, caching, load balancing ete
and Type 4 driver need not translate database calls to ODEC or native connectivity interface. Type 1
drivers are slow because they have to convert JDBC calls to ODBC through JOBC-ODBC Bridge driver
EEE
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 14:Naresh / Technologies JDBC By Mr. Nataraj
initially and then ODBC Driver converts them into database specific calls. Type 2 drivers give
average performance when compared to Type 3 & 4 drivers because the database calls have to be
converted into database specific calls. Type 2 drivers give better performance than Type 1 drivers,
Finally, to improve performance
1. Use Type 4 driver for applet to database communication.
2. Use Type 2 driver for two tiered applications for communication between java client and
the database that gives better performance when compared to Typel driver
3: Use-Type-4 driver if your-database doesn't support driver’ This is rare situation because
almost all major databases support drivers or you will get them from third party vendors.
4, Use Type 3 driver to communicate between citent and proxy server ( weblogic, websphere
etc) for three tiered applications that gives better performance when compared to Type 1 &
2 drivers.
|A thin wrapper around a millisecond value that allows IDBC to identify
ithis as a SQL DATE.
al ME
| |The basic service for managing a set of JDBC drivers.
DriverManager NOTE: The DataSource interface, new in the JDBC 2.0 API, provides |
another way to connect to a data so
DriverPropertyinfo ‘priver properties for making z a connection.
‘gaupermission “he permission for which the SecurityManager will check when code that
‘SQLPermission
} lis running in an applet calls one of the setLogWriter methods.
Time [A thin wrapper around java.util.Date that allows JDBC to identify this as a|
{SQL TIME value.
|A thin wrapper around java.util.Date that allows the JDBC API to identify|
|this as an SQLTIMESTAMP value.
he class that defines the constants that are used to identify generic SQL
|types, called JDBC types.
Array |The mapping in the Java programming language for the SQL type ARRAY. __
‘The representation (mapping) in the Java™ programming language of an SQL|
BLOB value.
The interface used to execute SQL stored procedures.
‘The mapping in the Java™ programming language for the SCrCLOB pe.
[A connection eon) ith a specific database. :Naresh i Technologies JoBc By Mr. Nataraj
Preparedstatement An object that represents a precompiled sat statement |
The mapping in the Java programming language of an SQL REF value, which is!
a reference to an SQL structured type value in the database.
‘A table of data representing a database result set, which is usually generated)
iby. executing a statement that queries the database. |
|An object that can be used to get information about the types and oulecra
[of the columns in a ResultSet object. |
ResultSetMetaData '
saubata
{An input stream that contains a stream of values represe
SQlinput fk SOL structured or distinct type |
[The output stream for writing the attributes of a user-defined type back tal
t
Satoutaes the database
[th
‘Statement | 1 object used for executing a static SQL statement and obtaining the results.
Statement [produced byit. :
eae |The standard mapping in the Java programming language for an SQL|
Struct, | structured type.
getConnection() Method:
‘* public static Connection getConnection(String url) throws SQLException
* public static Conriection getConnection(String url,String user String pwd)throws
SQLException
+ public static Connection getConnection(String url,Properties info}throws SQLException
‘The Architectural Difference Between the All Drivers
Figure 1. The Architectural
Difference Between Type 1 and
Type 2 Drivers. While Type 1 JDBC
drivers offer convenience of access
to ODBC data sources, they are
limited in their functionality and
performance. Type 2 JDBC drivers
are OS-specific and compiled, and
although they offer more Java
functionality and higher
performance than Type 1 drivers,
still require a controlled
environment
‘Naresh j Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshiter
Naresh i Technologies JDBC By Mr. Nataraj
Figure 2. The architectural
difference between Type 3 and
‘Type 4 drivers. Type 3 drivers
leverage the advantages of
middleware products to supply
heterogeneous database access,
and are a strong server-side
solution when that middleware
product runs on a single OS: Type 4
drivers provide fast and powerful
direct access from Java clients to
the databases themselves, but do
not provide some of the server-side
OS optimization found in Type 3
drivers.
TYPE 5 JDBC Driver
In recent years, the Java ecosystem has evolved quite dramatically on a number of fronts. As a
result, IT organizations are taking advantage of an array of new technologies that promise to
streamline Java development cycles and reduce operating costs.
In complex enterprise computing environments, however, everything is connected and not all
architectural components evolve in concert. Therefore, the introduction of advanced technologies
at specific points in the architectural stack often exposes many downstream technological
limitations.
As a result, businesses struggle to realize the return on investment promised by these new
technologies and in some cases, even experience problems that take them a step backward rather
than forward. Today, enterprise architects and developers experience this phenomenon when they
task overmatched Type 4 JDBC database drivers with the ever-increasing demands of the modem
Java environment. 7
The JDBC Driver: An Architectural Afterthought .
The JDBC API specification and the drivers it enables have certainly evolved over time, from the
original JDBC-ODBC bridge to the native-protocol Type 4 drivers that are so prevalent today. At this
point, however, that evolution is stagnant. The majority of Type 4 JDBC drivers-essentially offer the
same basic features and capabilities, so for many developers, JDBC access is essentially an
architectural afterthought that requires little attention.
This perception grew with the increasing adoption of Object-Relational Mapping (ORM)
technologies (JPA, Hibernate, and Spring, among others), or application servers such as JBoss that
sit on top of JDBC. With these modern development platforms, many developers no longer
Program directly to JDBC. :
With no access to underlying JDBC calls, developers almost never think about JDBC or what JDBC
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwiw.fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
means simply selecting a JDBC driver based on "checklisting.” If there is a free Type 4 JDBC driver
available, the driver is automatically assumed to be adequate for any use case.
Beyond ORM adoption, there have been other key technological advancements at work in the Java
universe. Virtualization now delivers massive scalability on an affordable growth curve, placing a
much higher value than ever before on optimum performance throughout the entire applicstion
stack. The increasingly complex features of relational databases frequently involve complicated and
proprietary implementations that make them all but inaccessible to most applications. These
strategic technologies are quickly finding acceptance in the enterprise marketplace, directing
renewed attention on JDBC components, and placing a revealing spotlight on the.shortcomings.on
Type 4 drivers as well as the negative impact these shortcomings have on IT performance and
costs,
Type 4 JDBC Driver: Glaring Limitations
Despite superiority over other JDBC architecture types, Type 4 drivers have failed to keep up with
the evolutionary advancement of complimentary Java technologies. As a result, most Type 4 drivers
come with glaring limitations in today's Java-based enterprise application environments,
+ Slow or Inconsistent Performance. The response time and data throughput performance of
‘many Type 4 drivers is poor or inconsistent, particularly when deployed into certain runtime
environments (such as different !VMs) or with modern data access models (ORMs and app.
servers).
+ Unavailable or Inaccessible Functionality. Enabling or tuning critical functionality with
many Type 4 JDBC drivers requires access to JDBC code, which is not available to
applications deployed with ORM frameworks or in app servers. New database or driver
functionality may also not be available across all supported JVM or environments.
+ Poor Resource Efficiency. Most Type 4 JDBC drivers use excessive amounts of CPU and
memory resources during data access. Tuning options, if available, are inaccessible or
fimited. This leads to excessive usage of CPU resources and a disproportionately large
memory footprint.
+ Application Deployment Restrictions. Most Type 4 JDBC drivers require multiple JAR files to
support different JVMs or database versions. They also typically require the deployment of
platform-dependent DLLs or shared libraries to support certain driver or database
functionality, limiting what environments they can be deployed to.
+ Proprietary Implementation. Many Type 4 JDBC drivers require proprietary code for
applications to leverage features such as BLOBs and CLOBs, high availability, and XA. As
more and more data sources must be accessed from a single application, the amount of
application code, and potential for bugs, increases significantly.
Many developers and architects find out the hard way, after a project has gone into production,
that even the most common Type 4 JDBC drivers exhibit most, if not all, of these limitations. As
businesses look to new technologies such as virtualization to improve performance and reduce
costs, the cost of dealing with the deficiencies of Type 4 JDBC drivers will only increase.
Type 4 drivers have failed to keep up with advancements
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit =18:chentogies JOBE By Mr. Nataraj
E vations: Taking the Next Step
There ~ sent afoot to address these limitations of Type 4 JDBC drivers by proposing the
atutionary path of JOBC drivers. Such a new step has been dubbed "ype 5"
where J 13 caused by today’s Type 4 IDSC drivers are solved but the benefits of Type 4
architecture a°@ maintained. One proposed definition states that Type 5 JDBC drivers shoutd
provide the following
+ Unrsstricted Performance. Should be able to easily handle the performance demands of
-a-driven-enterprise Java applications.
hancement. Should offer the ability to add, configure, and tune features
tiring access to or changes made to JDBC code.
Efficiency. Should use resources such as CPU and memory as efficiently as
e in multiple environments.
Ail-in-One Deployment. Should be able to support multiple environments without requiring
the deployment of multiple JAR files, or any native code libraries like DLLs.
* Streamlined Standardization. Should not require the use of extensions to the JDBC
specification no matter what functionality is required by the application.
Type 5 JDBC Drivers: Evolution or Revolution?
In an "evolutionary" step, Type 5 JDBC drivers wl build on all the positive features found with Type
4 products, Given the lack of advancement in the JDBC driver specification over the last decade, it’s
time that connectivity standards evolved with the myriad other advancements in the Java
programming language. By delivering on the promise of unrestricted performance, codeless
enhancement capabilities, optimized resource efficiency, an integrated deployment architecture,
and streamiined standardization, developers and architects that use Type 5 JDBC drivers can
mitigate the technical limitations imposed by outgunned Type 4 drivers that can no longer keep
pace within the greater Java ecosystem
JDBC drivers have not traditionally been viewed as a strategic investment for many businesses.
Type 5 JDBC has the potential to turn that trend on its head by offering businesses an easy way
take advantage of years of innovation in database features, data access models, and virtualization
technologies without requiring changes to the application. Whether the benefits sought are a
simplified data connectivity infrastructure, accelerated front-line productivity, or dramatically
reduced IT operational costs, businesses of all shapes and sizes should make it a priority to evaluate
Type 5 JDBC drivers and continue to push for innovation over stagnation.
JDBC Architecture
Two-tier and Three-tier Processing Models
The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies JpBc By Mr. Nataraj
‘Java Application
JDBC
Cheat Machine
DBMS proprietary protocol
See Database server
‘n the two-tier model, a Java applet or application talks directly to the data source. This requires a
JDBC driver that can communicate with the particular data source being accessed. A user's
commands are delivered to the database or other data source, and the results of those statements
are sent back to the user. The data source may be located on another machine to which the user is.
connected via a network. This is referred to as a client/server configuration, with the user's
machine as the client, and the machine housing the data source as the server. The network can be
an intranet, which, for example, connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a “middle tier" of services, which then sends the
commands to the data source, the data source processes the commands and sends the results back
to the middle tier, which then sends them to the user. MIS directors find the three-tier model very
attractive because the’ middle tier makes it possible to maintain control over access and the kinds
of updates that can be made to corporate data. Another advantage is that it simplifies the
deployment of applications. Finally, in many cases, the three-tier architecture can provide
performance advantages.
Figure 2: Three-tier Architecture for Data Access.
‘Server machine
‘ndnes ato)
DBMS propriciary proc!
i
Until recently, the middle tier has often been written in languages such as C or C++, which offer fast
performance. However, with the introduction of optimizing compilers that translate Java bytecode
Into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java
platform is fast becoming the standard platform far middle-tier development. This is a big plus
point, making it possible to take advantage of Java's robustness, multithreading, and security
features.
With enterprises increased using the Java programming language for writing server code, the JDBC
API is being used more and more in the middle tier of a three-tier architecture. Some of the
features that make JDBC a server technology are its support for connection pooling, distributed
——————_——————————————
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-22746666, www fo.com/nareshit 20%:Naresh i Technologies spec By Mr. Nataraj
transactions, and disconnected rowsets. The IDRC Pt is also what allows access to 2 data sour
from a Java middle tier.
HardCoding Verses GeneralizedCoding
HardCoding
Directly writing values in the program is called as hardcoding.
‘Simple example is find sum of two numbers:-
‘SumDemo.java(HardCoging)
public class SumDemo{
public static void main(StringfJargs){
int a=5;//hard coded value
int b=6;//hard coded value
int c=atb;
System.out.printin(c);
y
GeneralizedCoding
Taking (reading)values as input from extemal resources such as keyboard or properties file or xml
file...
SumDemo.java (GeneralizedCoding)
import java.util. Scann
public class SumDemo{
public static void main(String[]args}{
Scanner sc=new Scanner(System.in);
System.out.printf(“Enter 1 Number:”);
int a=sc.nextint();
System.out.printf("Enter 2nd Number:”);
int b= sc.nextint();
int c=atb; -
System.out.printf(c);
i 2
In’Realtime industry there are 3 types of environments for normal projects and 4 types for
environments for sensitive projects. They are:
1) Development Environment
2), Testing Environment
3) Pre Production Environment
4) Post Production Environment
The project is developed at development environment, after development, the same project must
be moved from development environment to testing environment for testing, after tested ok the
same project must be moved from test environment to preproduction, preproduction for
producing it to enduser(client). During testing, if the project is having some issue then, that project
from test environment must be taken back to development environment. In every environment.
separate database server is maintained, but all database server systems should have the same data
base management system software.
—_—_—_— eee es
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit ::21:Naresh { Technologies JDBC By Mr. Nataraj
For example : Oracletig
But one thing we which must be rembered is, if DataBase Server System ip address changes,
database SID, portnumber, username and password may change.
If the above values(SID, portnumber, username, password) are hardcoded in JDBC project.
Whenever the project is moving from one environment to another environment then to execute
that JDBC project we must modify the project source code.The project source code created in
development environment souldnot be modified in any other environment. If modification is
required, it should be done at deve'spment environment. To solve hard.coding problem.we must
use generalized coding Three types of generalized coding solutions are:
Solution one:
Read driver class name, database url, database username and database password from keyboard.
(This is not used in Realtime )
Solution two:-
Store driver class name, database url, database username and database password in properties file
and read this information from the properties file(Used in Real time).
ExampleProgram
1G AdbcApp
Be rc
8B com.nit
h-() adbeApp.java
~~ cb-config.properties
A ARE System Library [JavaSE-1.6)
E+ Referenced libraries
2-9 ojdbct4. jar -
and
PROIECTDesHtop
JdbcApp.java
package com.nit;
import java.io.FileInputStream;
import java.io.lOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util. Properties;
public class SdbcAnp { .
public static void main(String[] args) throws 1O£xception, ClassNotFoundException, SQLException {
FileinputStream fin=new
FileInputStream("E:\\ADV_JAVA\\JdbcApp\\src\\com\\nit\\db-config.properties");
Properties p=new Properties();
p.load(fin);
String driverclass=p.getProperty("driverclass");
String url=p.getProperty("url");
eee ee
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit
Jana insite maeNaresh i Technologies JDBC By Mr,
Nataraj
getProperty("dbuser");
getProperty("‘dbpassword');
Class forName(driverctass);
Connection con=DriverManager.getConnection(url,user,pass);
System.out.printin("connection"+ con);
}
}
db-config-properties
driverclass=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@nit-11:1521:xe
dbuser=system
dbpassword=manager
Solution three:- ¥
Store driver class name, database url, database username and database password in a XML file and
read this information from the XML file(Used in Real time).It is a recommended
‘Naresh ‘Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
Appl(Simple Select operation)
: *SelectTesti.java-----
{{SelectTest. java
import java.sql.*;
public class SelectTest1
{
public static void main(String args{])throws Exception
€ Hivegister jdbc driver
Class. Fortane("sun. jdbe.odbc. 3dbcOdbeDriver");
Connection con-Driversianager.getConnection("Jdbc:odbc :oradsn",
// create Staenent obj
Statenent stcon.cresteStatenent();
// execute the query
ResultSet rs=st executeuery("select * from student"
scott", “tiger");
/Iprocess the Resultset
while(rs.next())
{
}
Hclose all jdbc stream objects
rs.close();
st.close();
con. close();
Wimain
Jiclass
/I>javac SelectTest1. java
/D>java SelectTest1
system.cut.printIn(rs.getInt(1)+" "#rs.getString(2)+" “4rs.getString(3))
App2) Select Operation
J/selectTest2.java
import java.sql.*; //jdbe api
import java.utii.*; // Scanner class
public class SelectTest2
{
public static void main(String args[])throws Exception
{
J} vead inputs
Scanner se=new Scanner(Systen.i
Systen.out.printIn(“Enter city");
String city=sc.next(); //gives hyd
citys" ecitye” "5 //gives “hyd”
/iregister typel jdbc driver
Class. forWane( "sun. jdbc.odbc. JdbcOdbcbriver”) ;
[Establish the connection with Db s/w.
Connection con=briverManager.getConnection( "jdbc:odbe :oradsn”,, “scott”
Iicreate dbc Statenent obj :
Statenent st=con.createStatenent();
riger");
[/send and execute SQL Query in OB s/w
//select * from student where sadd="hyd"
ResultSet rssst.executeQuery("select * from student where sadd="*city);
[process the ResultSet
boolean flag=false;
while(rs.next () I=false){
System.out.printIn(rs.getInt(i)+" “+rs.getString(2)+"
Flagetrues
W/white
F(A
“4rs.getString(3))
false)
System.out.println("No records found");
‘Naresh’ Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 2Naresh i Technologies APPLICATIONS By Mr.Nataraj
67 //close jdbc objs
68 rs.close();
69 st.close();
78 con. close();
n W/main
72 yiclass
73 //>Javac SelectTest2. java
74 //>java SelectTest2
76 App3 )Select Operation
7 =
3
79 //SelectTest3.java
80 import java.sql.*;
Bi import java.util.*;
SelectTest3. java
82
83 public class SelectTest3
Ba {
35 public static void main(String args{])throws Exception
36 {
37 Head inputs
88 Scanner sc=nex Scanner(Systes.in
89 systen.out.printin("Enter start range no:
90 int stno=sc.nextint(); //gives 108
s System.out.println(“Enter end range no:");
2 int endno=sc.nextint(); //gives 200
93
9 //vegister typet jdbc driver
98 Class. forWane("sun. jdbc. odbc. 3dbcOdbeDriver");
96 [/Establish the connection with Do s/w.
7 Connection conDrivertanager.getConnection("jdbc :odbc:oradsn" "scott", “tiger");
98 [icreate Jdbe Statement obj
99 Statement st=con.createstatenent();
101 /Tprepare SQL Query
102 // select * from student where sno>=100 and sno.
103 String qry«"select * from student where snor=“+stno+" and sn
‘Systea-out.print1n(qry) 5
//send and execute SQL Query in DB s/w
ResultSet rs=st.executeQuery(qry);
//Process the ResultSet
boolean flag=false;
while(rs-next()){
'sendno;
flagetrue;
m1 system.out.println(rs.getInt(1)+" “#rs.getString(2)+" "+rs.getString(3))5
12 }
13 if(flag==false)
114 Systen.out.printIn(“Records not found");
us /Ielose jdbc objs
316 rs.close();
17 st.close(); .
iis con.close(); “
n9 Winain
120 )//elass
121 see
122 App4) Select Operation
123. weenne==s
SelectTest4. java
125 //SelectTest4. java
126 import java.sql.*;
127° inport java.util.*;
129 public class SelectTest4
20 {
231 public static void main(String args[])throws Exception
132 i
“Tiaresh Technologies Opp. Satyam Theatre, Amcerpet yd Ph O10 23746066, wunfoxcom/naresht
‘mmission i i enenniinrdnennnctt vente
BSESREENaresh i Technologies APPLICATIONS By MrNataraj
a
Fer) [read inputs
34 Scanner sc=new Scanner(Systen.in);
335 systen.out.printin(“Enter initchars of Enp nane");
136 String initchars=sc.next(); //gives AD
337 1 convert inpwt value as required for the SQL Query
238 initchars="""sinitchars#"X'"; //gives ‘ADK
Bo
ue H/register typel jdbc driver
141 Class. forNane( "sun. jdbc odbc. 3dbcodbeDriver");
a2 //stablish the connection with Db s/W.
443 Connection con=DriverManager.getConnection("jdbc:odbe:oradsn", "scott™, "tiger");
144 /icreate 3dbc Statement obj
us Statenent.st=con.createstatement();
M6
147 Mpeare Sau Query
14s //select enpno,enane, Job, sal fron enp where enane Like ‘ADR’
ug String gry="select enpno,ename,job,sal fron enp where enane like “+initchars;
350 systen.out.printIn(ary);
351 //send and execute QL Query in'0B s/w
152 Resultset rsest.executeguery(ary);
153 /[Process the ResultSet
154 boolean flag-false;
355 while (rs.next()){
156 flagetrue;
157 Systen.out.printIn(rs.getint(1)+" “#rs.getString(2)+" “#rs.getString(3)+" “#rs.g
158 }iwhile
159
160 Systen.out.printIn(“records not found"
161
162 //lose jdbc objs
163 rs.close();
164 st.close();
165 con.close()i
166 M/main
167 yy/fclass
168 nenwenes
169 AppS) Select Operation
ve
mi: a
472 //SelectTestS.java (with java coding standards)
173 /* App to get enp details based on the given designations
174 * Version : 1.0
175 * author: Tean-Nt
176 + pate : 2015-7-30 */
177 package con.nt. jdbc;
178 inport java. sqi-DriverManager;
179 inport java-sql Connection;
18 inport java.sql.Statenents .
181 import java.sql.ResultSet; .
382 inport Java.sql. Sgtexception;
183 inport Java.util.scanner;
184
185 public class SelectTests
186 {
187 public static void main(String argst]){
188 Conneétion con=null;
169 Statement stenull;
198 ResultSet rs=null;
191 Scanner se=null;
192 try{
193 /Iread inputs
194 sc=new Scanner(System.in);
395 string desgl=null,desg2=null, desg3-nul1;
196 3#(scl=null){
197 System.out.printin("Enter Desgi");
198 desginsc.next().toUppercase(); //gives CLERK
/nareshit
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd,cece erento
Naresh i Technologies APPLICATIONS By MrNataraj
199
200
201
202
203,
204
205
206
207
208
709
210
aaa
242
213
24
215
216
217
218
219
20
22a
222
223,
228
225
26
27
228
229
230
2a
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
bas
249
250
231
252
253
254
255
256
287
258
259
260
261
262
263
264
system.out.printin(“Enter Desg2");
desg2=sc.next().tolppercase(); //gives MANAGER
System.out.printin(“Enter Desg3");
desg3=sc.next().toUppercase(); //gives SALESMAN
yiat
/Iprepare Condition as required for SQL Query
71 CCLERK* MANAGER’ , "SALESMAN' )
‘String conde"(*"sdesgi+"", ""edesg2+"*, "+desg3+"
Iiregister jdbc driver
Class. forNlane("sun. jdoc.odbe, JébeOdbeDrivert");
//Establish the connection
con=DriverHanager..getConnection("Jdbe:odbe:oradsn”, “scott”, "tiger
Mcreate. Statement obj
1 (con!=nul1)
stecon.createStatenent(
Iiprepare SQL Query
//select eapno,enane,job,s21 fron enp where job in(*CLERK' ,‘MANAGER*,
string qry="select enpno,enamé, job,sal fron enp where job in*sconds* orde
System.out.printin(qry);
H/send and execute SQL Query. in DB s/w
if (st!enull) F
rsest.executequery(qry); Uh
//process the ResultSet
boolean flag-false;
if (rs tenull)¢ /
while(rs.next()){ :
Systen.out.printin(rs.getInt(1)+
Flag-true;
‘srs.getString(2)+" “#rs.getstr
Miuhtle
MAF
system.out.printIn("Records not found");
Yitey
catch(ClassNotFoundexception cnf){ //for known exception
System. out .printin(cnf.toString())
} :
catch(SQLException se){ “'//for known exception
se.printStackTrace();
catch(Exception e){ _//for unknown exception
e.printstackTrace();
a
‘inally(
V/close jdbc objs
teyt
if(rs!=null){
rs.close();
}
catch(SQLexception se){ a
se.printStackTrace();
t
: try
if(stlenull){ a
st.close(); ~
}
+
catch(SQLexception se){
se.printStackTrace();
+
try
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 27: .Naresh i Technologies APPLICATIONS By Mritataraj
265
266
267
268
269
270
271
272
273
274
275
276
277
278
278
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
237
298
299
300
301
302
303
304
305
306
307
308
309
310
BAL
312
33
314
315.
316
317
318
319
320
321
322,
323
324
325
326
327
328
329
330
if(cont=null){
con.close();
}
}
catch(SQLException se){
‘se.printstackTrace();
w11){
sc.close();
+
catch (Exception e){
e.printStackTrace();
}
Wi finally
main
Viclass
V/yjavac -d —. SelectTest4.java
/P3ava__com.nt.jdbc.SelectTest4
Apps ) Select Operation
SelectTest6.java-
package com.nt;
import java.sql.connection;
import Java. sql-Drivertanager;
import java. sql.statement;
import java. sql-ResultSet;
import java. sql. SQLException;
inport java.util.Date;
7* Application that gives employee details who is having highest salary
* Version: 1.0
= Author :Team -s */
public class SelectTests
{
public static void main(String args[]){
Connection con=null;
Statement st=null;
ResultSet rsenull
tryf
[register jdbc driver with DriverMtanager Service
Class: ForNane("sun. jdbc odbc. JdbcodbeDriver");
[Establish the connetion
con=DriverManager .getConnection(*jdbc:odbc:oradsn", "scott" ,“tiger");
1 create Statenent obj
4¢(con!=nu2)
con. createStatenent();
3
H1send and execute SQ Query in OB £/m
if(stl=null)
rssst.executeguery("select enpno,enane,sal, job fron enp where sale(select
Hiprocess the Resultset obj
=n) {
wedle(s.next()){
Systen.cut.printIn(rs.getint(1)+" "4rs.getString(2)+"
ent
while
we
if ent:
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshitNaresh i Technologies APPLICATIONS By Mr.Nataraj
331
332
333,
334
335
336,
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353,
354
355
356
357
358
359
360
361
362
363,
364
365,
366
367
368
369
370
371
372
373
374
375,
376
377
378
379
380
381
382
383,
384
385,
386
387
388
389
390
391
392
393,
394,
395,
396
‘System.out.println("No Records Found");
wieey eS
ich(ClassNotFoundéxception cnf){ // To handle known Exception
nf. printStackTrace();
catch(sgLexception se) { // To handle known Exception
se.printStackTrace();
>
catch(Exception,e){ // To handle unknown Exceptions
e-printStackTrace();
d
Finally{
try
if (rst=null)
rs.close()3
catch( Exception e){
e.printstackTrace();
d
try!
wll)
: st.close();
}
catch(Exception e){
e.printstackTrace();
}
tryt
4#(cont=nul1)
con.close();
catch(Exception e){
e.printStackTrace();
}
}//Finally
}fmain
Viclass
I/yjavac -d. SelectTestS. java (Compilation)
I/yjava_con.nt.SelectTest5 (Execution)
Agp7) Select Operation
-SelectTest7. java
//selectTest?.java (Application that gives Emp Details based on given deptno)
package com.nt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql-Resultset;
import java.sql.SQLexception;
import sql.Statenent;
import java.util.Scanner;
public class SelectTest7{ i
public static void main(String{] args){
Scanner sc#null;
Statement 51
J/cead inputs
scenew Scanner(System. in);
system.out.printIn("Enter dept no’
int _deptno=0;
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www:fb.com/nareshit 29:se
Naresh i Technologies APPLICATIONS j \
a 1
397 ‘s£(sel=null){ {
398 deptrioxsc.nextint () ;
399 }
400 // register jdbe driver with Drivertanager service
401 Class. forName("sun. jdbc.odbc. JdbcodbeDriver") 5
402 /Jestablish the connection
403 coh=Drivertanager.getConnection(" jdbc :odbe:oradsn", "scott", “tiger”
404 [Create Idd Statenent obj
405 $(con!=null)
406 stecon, createStatenent();
407 H/send and execute SQL Query in DB s/w
408 if(stl=nil1)
409 Feast .executeQuery("select empno,ename,job,sal from emp where deptno
ate
4a « 1£(rstenull) {
a boolean flagefalse;
413 while(rs.next()){
au Flagetrues
ais systen.out.printin(rs.getint(1)*" “+rs.getstring(2)+" “+rs.getstring(3)+"
416 } t
417
aig i¢(flagesfalse)
419, Systen.out.printIn("Records not found");
42a
aaa Mise
a2 Witey
423 catch(ClassNotFoundexcéption cnf){ //To handle known exception
428 cenf.printstackTrace();
425, y
426 catch(sQlexception se){ // To handle known exception
427 se.printStackTrace();
428 } i
429 catch(Exception e){ '// To handle unknown exception
430 e,printStackTrace();
431 3
432 Finally(
433 //Close jdbc objs
434 try{
435 if (rst=null)
436 rs.close();
437 Mitry
438 catch(Exception e){
439 + e.printstackTrace();
440 +
401
442 tryf
443 i¢(stlenvl1) .
aaa st.close();
445 Witry
446 catch( Exception e){
447 ‘e.printStackTrace();
448 y
44g
450 try
451 4f(con!=nul1)
452 con.close();
453 }
454 catch( Exception e){
455 e.printStackTrace();
456 ?
457 y/Finally
458 Wimain
459 -}//class,
460 //>javac -d . SelectTest7. java
461 //>java_com.nt.SelectTest7
462
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fD.com/nareshitNaresh i Technotogies APPLICATIONS By Mr.Nataraj
a
43 saneenereenes
464 Appa(Application to call SQL Aggragate. Function)
465 ee
466 AggragateTest. java
467 //hggragateTest. java
468 inport java.sql.
469° import java.util.
478 import java.io.*;
471 public Class AgeragateTest
a7
473, public static void main(String args[])throws Exception
474 {
475, Class. forName( "sun. jdbc.odbc. IdbcOdbcdriver") ;
476 Connection. con=DriverManager. getConnection(Jdbcrodbc:oradsn' y"tiger");
477 1/ create Staement obj
478 Statement st=con.createStatenent();
473 // execute the query
480 ResultSet rsust.executeQuery("select count(* ) from emp");
481, if(rs.next())
432 {
483 System.out.printIn("the Number of Records are :"+rs.getInt(1));
484 ?
485 //close all jdbc stream objects
486 rs.close();
487 st.close()}
488 con.close();
489 M/nain
49@ }//class
491 waneneneneen:
492 App9(Simple Delete operation taking sno value as criteria)
493 =
494 +
495 //DeleteTest.java
496 import java.sql.*;
497 import java.util.*;
498 public Class DeleteTest
499 {
see public static void main(string args[])throws Exception
501 {
502 1 read Anput values from key board
503 Scanner sc»new Scanner(Systen. in);
504 Systen.out .printIn(“Enter student no to delete record");
505 int nosse.nextInt();
506 .
307 1/ create jdbc connection
S08 Class. forNane( "sun. jdbc.odbc. JabcOdbeDriver");
59 Connection con=Drivertanager .getConnection( "fdbc:odbc:oradsn” ,"scott™,"tiger");
510
su //disable autocomnit mode on DB s/w
512 con. setdutoConnit (false);
513
54 Hereate jdbc Statenent obj
sis Statenent st=con.createstatenent();
516
517 Hiprepare query
518 String qry="delete fron student where sno="4n0;
519 System. out .println(qry);
520
521 11 execute the query...... ,
522 int resultest .executeUpdate(ary);
523
524 Hconmit or roliback
S25. con.conmit(); //(or) — con.roliback();
526
527 I process the result
528 Af(result==0)
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
528 ‘System.out.printin("record not found to delete");
530 else
531 System.out.printIn(result+” no.of Record(s) found and deleted");
532
533 Hclose jdbc objects
534 st.close()}
535 con.close();
536 Winain
537 W/class
538 =
538 App10(Simple Insert operation)
540 -
sai InsertTest.java~ -
542 package con.nt
$43. //TnsertTest.java (having Coding standards)
54a /* Application to insert record into DB table
545 * version :1.0
$46 * author: Tean-s */
547 import Java.util.Scanner;
548 import java-sql.DriverManagers
$49 inport javasql Connection;
550 inport java-sql.Statenents
551 import Java.sql. SQLException;
4
i
Fi
5
5
5
5
é
6
6
6
6
‘
6
6
é
6
6
6
6
6
6
6
é
6
6
6
é
&
6
‘
é
&
6
s
$52
553 public class InsertTest
ssa {
555 public static void main(String args[])
356 C
557
558
559
560
561
562 1 read record related input values from keyboard
563 int no=9;
564, String name=null, addrs-null;
565 sc=new Scanner(Systen.in);
566 4#(scl=null)
567
568 systen.out.printin(“Enter student no");
569 no=sc.nextint()5
570 System.out.printin(“Enter student name");
571 nane=sc.next();
572 Systen.out.printIn("Enter student address");
573 addrsesc.next();
574 wat
575 /Iprepare variable values as required for the SQL(insert) query
576 nane=*'"+nane+""*;
37 addrse"'"+addrs+"
578
379 1] create jdbc con with 0B s/w
580 Class. forName("'sun. jdbc odbc. JdbcOdbcDriver");
sei con=DriverManager..getConnection(*jdbc:odbe:oradsn neiger")
582
583 1/ create jdbc statement obj :
584 4¢(cont=null)
585 st=con, createstatement ();
586
587 J/prepare example query with direct values
588 //String qry="insert into student values(101, ‘raja, *hyd')*;
589
590 //frane the insert query with variables
591 String qry="insert into student values("+no+","+name+","“+addrs+")";
592 System. out. printIn(ary);
593
594 11 send and execute the query in 08 s/w
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit595,
596
397
598
599
608
6ot
602
603
604
605
606
607
608
609
610
eit
612
613,
614
615
616
617
61s
619
620
621
622
623
624
625
626
627
628
629
638
631
632
633,
634
635
636
637
638
639
640
sat
642
643,
64a
645,
646
647
cag
649
650
651
652
653
654
655
656
657
658
659
660
Naresh i Technologies APPLICATIONS By Mr.Nataraj
int res=0;
if(st¥enul1)
ressst.executeUpdate(ary);
J/process the result
if(res==0)
system.out.println("Record insertion Failed");
else
System,out.printin("Record inserted");
itry
catch(ClassNotFoundException cnf) // to handle known exception
{
cnf.printstackTrace();
3
catch(SQLException se) // to handle known exception
t
se.printStacktrace();
}
catch(Exception e) // to unknown exceptions
{
e.printstackTrace();
}
Finally
t
//elose jdbc objects..
try
if(stlsnull)
st.close();
3
catch(SQLException se)
{
se.printstackTrace();
>
try
{
4€(con!=nul1)
con.close();
}
catch(SQLexception set)
‘
sel.printStackTrace();
}
3 /#inally
Wnain
Hiclass :
J rjavac -d . InsertTest. java
//>java com.nt InsertTest
App11(Progran to update the record based on the student number)
package com.nt3
/WpdateTest. java (with ‘coding standards)
/* App to update student details
* version : 1.0
* author : Tean-s*/
UpdateTest java
import java.util.Scanners
import java.sql .OriverManagers
import Java.sql.connection;
Amport java. sql-statement;
import java.sql.SgLexception;
‘Naresh i Technologies, Opp. Sotyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/naresNaresh i Technologies APPLICATIONS. By Mr.Nataraj
661
662 public class UpdateTest
663 {
664 public static vaid main(String ares(])
665 {
666 Connection consnul1;
667 Statenent st=nuli;
668 Scanner scenull;
669 try
670 {
671 // read input values from keyboard
672 scenew Scanner(Systen. in);
673 int nose;
674 ‘String nane
675 String addr:
676 if (sctenut)
677 {
678 system.out.printin(“Enter existing student nunber");
679 no=sc.nextint();
680 System.out.printin("Enter few nane:*);
681 name=sc.next();
682 systen.out.println("Enter new address:");
683 addrsesc.next()3
684 Var
685
686 Jf register jdbe driver and establish the connection
687 Class. forNane(“sun. ide .odbe. JdbcOdbcbriver");
688 con-DriverManager .getConnection(*jdbc:odbe:oradsn”, Scott", "tiger";
689 /[create Statement obj
698 4#(cont*nul1)
691 stecon.createStatement();
692
693 11 frane example ary with direct values
694 J/string qry="update student set snane=*naharaja’ ,sadd="vizag' where snos1et
695 String qry="update student set snane psadde"*4addrss""* where sno=".
696 system.out.printIn(qry);
697
698 /Isend and execute the gry in db s/w
699 int res=o;
700 4if(st!=nul1)
Jor res=st .executeUpdate(ary);
702
703 II process results
704 iF (res==0)
705 t :
706 System.out.printin(“record not found");
787 }
708 else
708 {
710 System.out.printin(res+*no.of records are updated");
ma
nz ~ Mitry
713 catch(ClassNotFoundéxception cnf)//handles known exeption
714 {
71s enf.printStackTrace()s
716 }
nz catch(sQlexception se) //handles known exception
738, ot
ng se. printStackTrace();
720 .
7a cateh(Exception e) //handles unknown exceptions
722 {
23 e.printStackTrace();
724 r
25 finally
726 {
"Naresh Technologies, Opp. Sotyam Theatre, Ameerpet, Hyd, Ph: G40-23746666, www fo.cam/nareshiNaresh i Technologies APPLICATIONS By Mr.Nataraj
n7 7/close jabe objs
ns try
ns i
730
71 st.close();
732 i J
33 catch(SQLexception se)
Ba re
735 se.printstackTrace();
736 }
27
738 try
738 {
7a 4f(con!snutl)
a1 : con.close();
702 3
703 catch(SQlexception se)
ma re
ms se.printStackTrace();
746 ?
787 y/#inally
m8 Wimain
749 }//class
750 //>Javac -d . UpdateTest. java
751 //>Java con.nt.UpdateTest
752 = - ——
753 App12 (App to execute both select and non-select SQL Queries)
754 a =
BS + ~SelectNonselectTest. java
756 //SelectNonSelectTest. java (Example on execute(-) method)
757 import java. sql.*3
758 inport Java-util.*;
759 public class SezectNonselectTest
We
764 public static void main(String args[])throws Exception
762 t
763 1/ read sql query (any) fron keyboard
764 Scanner sc=new Scanner(System.in); $
765 System.out.printIn(“Enter the qry*);
766 string arysse.nextLine();
787
768 11 create jdbc con
769 Class. fortiane(*sun. jdbc. odbc. JdbcOdbcOriver
778 Connection -con=Drivertanager .getConnection("jdb
m7 // create jdbc statement obj
™m Statement st=con.createStatement();
73
774 //send and execute gry in db s/w
78 boolean flag=st .execute(ary);
776 // gather and process the result
™ if(Flagestrue) // when select sql ary is executed
778 {
m7 ResultSet rsest.getResultset(); ‘
780 while(rs.next())
781 { :
782 System.out.printIn(rs.getInt(1)+" “4rs.getString(2)+" “4rs.getstri
783 }
784 rs.close();
785 id
786 else // when non-select gry is executed
787 {
788 int rowcount=st.getUpdateCount();
788 Systen.out.printIn(“the no.of records that effected"+rowcount);
798 e
791 ,
792793
794
798
796
797
798
738
800
et
802
803
804
205
806
807
808
809
aie
ain
B12
813
aia
ais
816
817
sig
819
820
821
822
823,
24
825,
826
827
528
829
830
531
832
833
834
835,
836
837
838,
839
841
842
843.
84a
845
846
847
84g,
849
850
851
852
853
asa
855
856
857
358
Naresh i Techriologies APPLICATIONS: By MrNataraj
‘st.close();
con. close();
dimain
iclass
‘App13 ) CreateTable
-CreateTableTest. java~
package com.nt. jdbc; ‘
import java.sql.Connection;
inport java.sql.DriverNanager;
inport java.sql.Statenent;
public class CreateTableTest {
public static void main(Stringl] args)throws Exception {
Iivegister jdbe driver
Class. forWane(*sun. jdbc.odbc. dbcodbeDriver");
//fstablish the connection
Connection con=Drivertanager.getConnection(*jdbc:odbc:oradsn”, "scott", “tiger")5
J/create Statement obj
Statenent, st=con.createStatenent();
[/send and execute SQL Query in DB s/w
int resultust .executeUpdate(“create table tenp(coll nunber(5))");
//process the result
AF(result==0)
Systen. out .println(“Table not created");
else
system.out.printin(*Table created");
M1close jdbc objs
st.close();
con.close();
Wimain
J/class
Appl4) Drop table Test
DropTableTest. Java
package com.nt. jdbc;
import java.sql.Connection;
Inport java.sql.DriverNanager;
inport java.sql-Statenent;
import java.util.Scamer;
publicclass DropTableTest { °
public static void main(String[] args)throms Exception ¢
[read inputs
‘Scanner ew Scanner(System. in);
systen.out.printIn(“Enter db talbe");
String tabssc.next()}
HIregister jdbc driver
Class. forName(“sun. jdbc. odbc. IdbcOdbcDriver™
[/Establish the connection
Connection con=DriverManager .getConnection("jdbc:odbc:oradsn", "scott", "tiger");
[create Statenent obj
Statenent st-con.createStatement();
[send execute SQL Query in DB s/w
int result-st.executeUpdate("drop table "+tab);
Hiprocess the result
if(resulte=0)
System.out.printin(
fable not found");
0-23746666, www. fo.com/nareshit 3%
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerset, Hyd, PNaresh i Technologies APPLICATIONS By Mr.Nataraj
859
68
61
362
862
864
865
866
867
368
369
370
373
872
373
274
875
376
877
378
373
389
ast
882
383
38¢
385
386
287
888
89
290
891
292
893
204
895
856
897
898
899
900
901
902
903
904
905
906
907
908
909
910
on
912
913
914
915
916
917
918
919
920
921
922
923,
924
else
System.out.printIn("Talbe dropped");
/[close jdbc objs
st.close();
con. close(};
}imain
Hielass
AppiS(Progran to insert multiple records using PreparedStatenent)
HPstinsertTest java
import java.sql.DriverManager;
inport java.sql.Connection;
inport java.sql.Preparedstatement;
inport java.sql.SQLexception;
Anport java.util.scanner;
stInsertTest java:
public class PstInsertTest
7
public static void main(String args{])
Preparedstatenent :
try
{
wll
d/vead input value fron key board
Scunew Scanner(System.in);
int n=0;
if (se!=null)
‘
system.out.println(“Enter no.of students");
nesc.nextInt()5
}
JIcreate jdbc con object
Class. forNane(“oracle. jdbc driver .Oraclebriver”);
con=DriverManager .getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott
/1 create Preparedstatenent obj
if (cont=null)
ps=con.prepareStatement(“insert into student values(?,?,2)*)3
// read each student details from keyboard, set them to query
71 and execute the query
if(ps!enull. && scl=nul1)
{
for(int ietjicen;++i)
{ :
system.out.println("Enter “+i+" student detdils");
System.out-printIn( “Enter student-no™);—
nt nozsc.nextInt()5
syster.out.printin("Enter student nase")
String nane=sc-next();
systen.out.println(“Enter student address");
String addrssc.next();
//set these values query place holders
ps.setInt(1,no); ;
ps.setString(2,namc);
ps.setstring(3, addrs);
HJexecute the query
int reseps.executeUpdate()
gies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit,Naresh i Technologies APPLICATIONS. By MrNataraj
925)
926
927
928
929
936
931
932
933
934
935,
936
937
938
939
240
941
942
943
944
945,
946
947
948
943
950
951
952
953
954
955
956
957
358,
959
960
961
962
963
964
965
966
967
968
968
978
ova
972
973
974
975
976
977
978
979
988
981
982
983
984
985
986
987
988
989
990
TF(res==2)
systen.out.printIn(it*student details are not insert
else
system.out.printIn(i+"student details are inserted”
W/for .
wit
Mitry
catch(ClassNotFoundexception nf) // to handle known exceptions
i
enf. printstacktrace(); .
}
catch(SQLException se) // to handle known exceptions
se.printStackTrace();
}
catch(Exception e) // to hanlde unknown exceptions
ui
e.printStackTrace();
; ;
Finally ‘
C
[/close jdbe stream objects
try
c
if(ps!-=null)
ps.close();
}
catch(SQlexception se)
{
se.printStackTrace( 3
}
try
{
if(con!*nul1)
con.close();
}
catch(SQLException se1)
t ?
se1.printStackTrace();
}
W/#inally
V/main
jiclass
‘App16) (Showing SQL Injection Problen)
Loginapp. java
/* 0B table in oracle :
userlist
uname ve2 Pad vez
raja hyd
ranesh hyd
”
import java.sql.*3
import java.util.*;
public class Loginapp
{
public static void main(String args[])throws Exception
{
/Ivead inputs
Scanner_scenew Scanner(system.in);
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 38:Naresh i Technologies APPLICATIONS. By McNataraj
991
992
993
994
995
996
997
998
999
1000
2001
3002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023,
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033,
1034
1035,
1036,
1037
1038
1039
~ 1040
1041
1042
1043,
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053,
1054
1055
1056
System.out. printIn(“Enter usernane:")}
String user=sc.nexttine(); //gives raja
System.out.printIn("Enter Password: ");
String pasc-se.nextLine(); //gives rao
// there is no need of coverting input values...
U1 register jdbc driver and establish the connection
Class. forttane("oracle. jdbc .driver OracleDriver");
Connection consDrivertanager.getConnection("jdbc:oracle: thin:@localhost:1521:xe" "sc:
Iiprepare SOL Query
String gry="select count(*) fron userlist where unan
[/create Jdbc Statenent obj
Statement st=con.createStatenent();
/isend and execute the Query in DB s/w
ResultSet rs=st.executeduery(ary);
Hiprocess the ResultSet
int cnt=05
if (es.next())
{
}
‘suser+"' and pwd:
enters. getint(1);
if(cnt==8)
System.out.printIn("InValid Credentials");
else
systen.out.printIn(“Valid Credentials");
I/elose jdbc objs
rs.close();
st.close();
con.close();
Winain
yielass
71 >§avac Logindpp. java
//>java Logindpp
enter user nane:raja’ --
enter password : hydi (wrong password)
output: Valid Crendentials ( SQL Injection problen)
Appi7 (Solving SQL Injection Problem)
LoginAppt.. java~
/* 0B table in oracle
userlist
uname vc2
raja
ramesh
/
import java.sql.*;
import Java.util.*;
public class Loginappt
{
public static void main(String args[])throws Exception
t
[/vead inputs
Scanner sc=new Scanner(System.in);
systen.out.printIn("Enter username: ")3
string user=sc.nextLine(); //gives
system.out.printIn("Enter Password:
String passesc.nextLine(); //gives ra0
// there is no need of coverting input values..
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph 040-23746666, www.fe.com/nareshitNaresh i Technologies APPLICATIONS By McNataraj
1087
1058
1059
1060
1061
3962
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073,
1074
1075
1076
1077
1078
3079
1086
1081
1082
1083,
1084
1085
1086
1087
ese
1089
1090
1091
1092
1093,
1094
1095
2096
1097
1098
1099
3100
1101
1102
1103
1104
1105
1106
3107
108
1109
1110
aa
prety
m3
Free
aus
1116
4117
1118
1119
1120
uaa
1122
7/ register jdbc driver and establish the connection
Class. forName(“oracle. jdbc driver Oracledriver®);
Connection con=DriverManager.getConnection("idbc:oracle:thin:@localhost :15212
Horepare SQL Query
string qry="select count(*) from userlist where unames? and pud=?";
/[create Idbc Preparedstatenent obj
PreparedStatement ps=con.prepareStatement(qry) ;
// set values to Query parans
ps.setString(1,user);
ps.setstring(2,pass);
//send and execute the Query in DB s/w
ResultSet rs=ps.executeQuery();
{/process the ResultSet
int cnt=0;
if(rs.next())
{
enters.getInt(1)5
)
i (cnt=u0)
System. out.printIn( "Invalid Credentials");
else
system.out.print1n( “Valid Credentials");
I/elose abe ob3s
rs.close();
ps.close();
con.close();
3/main
ielass
//>javac Logindept. java
7/>ava Logindpp1
enter user nane:raja‘ --
enter password : hydi (wrong password)
InValid Crendentials (No SQL Injection problen)
//oateInsert.java
import java.util.*;
import java.sql.*;
public class DateInsert
{
public static void main(String args[])throws Exception
{
// ead Anput values fron keyboard
Scanner scenew Scanner(System.in);
systen.out.printin("Enter person no");
int nowse.nextInt();
systen.out.printin(“Enter person nane:
String name=sc.next();
system. out.printin( “Enter DOB(dd-#M-yy)")
suring sdobesc next
System.out.print1n( "Enter 003 (yyyy-tt-dd)");
String sdoj=sc.next();
HIconvert String Date values to java.sql.Date class bjs
11 for DOB
SimpleDateFormat_sdfisnew SimpleDateFormat("dd-NM-yy'
‘Naresh Fechnologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwfechnologies APPLICATIONS _ By MrNataraj
java.util.Date udob»sdf1.parse(sdob);
java.sql.date sadot
lew Java. sql .Date(udob.getTimes));
1/for 003 (yyyy-Hs-dd)
java.sqi.vate sadoj=java.sql.Date.valueot(sdoj)
Lcreate jdbc con object
Class. forWame( “oracle. jdbc.driver.Oracledriver") ;
Connection consOriverManager..getConnection("idbc:
racle: thin:@localhost:1522:xe",
/Icreate PreparedStatement obj pointing to insert query
PreparedStatement ps=con.prepareStatement(“insert into person_tab values(?,?,2,?)"
H/set values to the parameters of query
ps.setInt(1,n0);
ps. setString(2, name);
ps. setDate(3,5qdob) 5
ps.setDate(4,sqdoj);
Hfexecute the query
int res=ps. executeUpdate
/Iprocess the result
iF(reses0) i
system.out.println("record not inserted");
else
System. out .printIni
‘record inserted"); ‘
Hclose jdbc objs
ps.close();
con.close();
Hinain
Viclass
//>$avac OateInsert. java
//> java DateInsert
DateRetrieve.java-
[oateRetrieve.
sport java.sql.*;
import java.util.*;
import java.text.*;
public class DateRetrieve
{
public static void main(String args[})throws Exception
{
JI create jdbc con obj
Class. forName(“oracle. jdbc.driver.OracleDriver");
Connection con=DriverNanager.getConnection(" jdbc: oracle: thin:@localhost:1521:xe", "sc
J/create jdbc Statement object
Statement st=con.createStatement();
J/ execute the query
ResultSet rsest.executeQuery("select * from person_tab");
//process the ResultSet
while(rs.next())
{
int no=rs.getInt (1);
String name=rs.getString(2);
Java.sql.Date sqdob=rs.getdate(3);
Java.sql.Date sqdojers.getDate(4);
//convert java.sql.0ate class objs to java.util.Date class objs
java.util.Date udob= (java.util. Date)sqdob;
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit1189
1190
sist
3192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
R03
1204
1205
1206
1207
1208
1209
1210
1244
1222
1213
aaa
az,
1216
1217
1218
1219
1226
1221
1222
1223,
1224
3225
1226
1223
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
3242
1243,
4244
1245
1246
1247
1248
1249
1250
1251
1252
1253,
1254
Naresh i Technologies “APPLICATIONS By MrNataraj Pot
java.util.Date udoj=(Java.util .Gate)sqdo};,
//convert java.util.Date class objs to String date values
SimpleDateFormat sdft-new SinpleDateFornat ("MiM-yy-dd")
String sdob=sdf1,format(udob) ;
SinpleDateFormat. sdf2-new SinpleDateFormat ("yyyy-dd-Mt");
String sdoj=sdf2.format(udoj);
systen.out.printIn(no+” “snamet" —“+sdob+"—“sdoj);
Winhite
I/elose jade objs
rs.close();
st.close();
con.close();
Vimain
Hiclass *
‘Appi9 (working with Large objs (BLOB)
~ Photoinsert. Java
/* create table enpali(eno nunber(4),enane varchar2(26),esalary number(7,2), ephoto blob) ;*/
import java.sql.*5
import java.io.*;
class PhotoInsert
{
public static void main(String args[])throws Exception
x
/Ivegister jdbc driver and establish the connection
Class. forNane(“oracle. jdbc driver .Oraclebriver");
Connection con=DriverNanager .getConnection( "jdbc :oracle:thin:@localhost:1521:xe",
/[create PreparedStatenent obj
PreparedStatenent ps=con.prepareStatement("insert into enpall values(?,?,?,2)")s
ps.setInt(1, 234);
ps.setstring(2, "raja");
ps. setFloat(3,5000);
scott",
File fenew File(*tips.gif");
FileInputStrean fisenew FileInputstream(f);
ps.setBinaryStream(4,fis, (int)#.length());
I/execute the query
ps.executeUpdate();
Systen.out.printIn("Photo Inserted");
J/close the jdbc obj
fis.close();
ps.close();
con.close(}3
Yimain
Miclass
-PhotoRetrieve.java-
inport java.sql.*;
import java.io.*5
public class PhoteRetrieve
I Se
public static void main(String args[])throus Exception
{
JJregister jdbc driver and estblish the connection
Class. forNane( “oracle. jdbc.driver .OracleDriver") ;
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott",
/Icreate 3DBC Statement obj
Statement st=con.createStatement();
71 execute the SQL Query -
ResultSet rsest.executeQuery("select * from enpall");
‘Noreshi Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies APPLICATIONS By Mr.Nataraj
[Jprocess the ResultSet obj
sF(es.next0)
//get InputStream
InputStream in=rs.getBinaryStream("ephoto");
/icreate Destination File
FileOutputstream fos=new FileOutputstream("nenpict.gif");
//Buffering based logic to complete photo retrivening
int bytesRead=a)
byte (] buffersnew byte[ 4096];
while( (byteskead=in.read(buffer))1=-1)
q {
y
system.out.printin(“photo is stored in neupict.gif");
J/close jdbc objs
fos.close();
in.close();
rs.close();
st.close();
con.close();
wag
Yimain
Wiclass
fos.urite(buffer,@, bytesRead);
‘App20) Working with Large objs (CLOB) i
package con.nt. jdbc;
-CLoBInsert.java-
import java.io.File;
import java. io.FileReader;
import java.io.Reader;
import java.sql.Connection;
inport java.sql.DriverNanager;
import java.sql-Preparedstatemient;
import java.util.Scanner;
public class CLoaznsert {
: public static void main(string{] args)throws Exception {
° //read inputs
Scanner scenew Scanner(System.in);
systen.out.println(“Enter sno");
int nosse.nextIne();
systen.out.printin(“Enter snane");
String sname=sc.next();
system.out.println(*Enter address
String saddesc.next();
systen.out .printin("enter resume path");
string
U/vegister jdbc driver .
Class. forName( “oracle. jdbc driver,QracleDriver*); :
J/€stablish the connection 1
Connection consDriverNanager .getConnection( “jdbcroracle:thin:@localhost:1521:xe", “scott™
//create Prpearedstatenent obj
PreparedStatement ps=con.preparestatement("insert into studentAll values(?,?,?,2)*
I Create java.io.File obj
File file-new File(resumePath);
long lengthefile.length();
(/create Réader obj pointing resume
Reader readersriew FileReader(file);
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746656, www.fo.com/naresNaresh i Technologies APPLICATIONS By Me.Nataraj
3320 7/set paran values(?) to Query
1322 ps.setint(1,no);
1323 ps.setString(2,snane);
1324 ps.setString(3,sadd) ;
3325 ps.setCharacterstream(4, reader, (int) length);
1326 7/ps.setClob(4, reader, length) ;
3327 //execute the Query
1328 int result=ps.executeUpdate();
1329 // process the Result
1330 AF(result==e)
1331 Systen.out.printIn("Record not inserted");
1332 else
1333 system.out.printIn(*Record inserted”);
4334
1335 I/close jdbc objs
1336 reader.close();
1337. ps.close();
1338 con.close();
1339 }
1340
1341}
3342 CLebretrieve. java-
1343 package con.nt. jdbc;
1344
1345 import java.io.FileWriter;
1345 import Java. io.Reader;
1347 import Java.io.Writer;
1348 import Java. sql.Connection;
3349 import java. sql.Drivertanager;
1359 import Java. sql.Preparedstatement;
1351 import java. sql-ResuitSet;
1352 import java-util.scanner}
1353
1354 public class CLOBRetrieve {
1355 public static void main(string[] args)throws Exception {
1356 //vead inputs
1357 Scanner scenew Scanner(Systen.in);
ase System.out.printIn("Enter student no");
1359 int nossc.nextInt();
1360 //stablish the connection
1361 Class. forName(“oracle.jdbc.driver OracleDriver") ;
Bez Connection con«Drivertanager..getConnection(" jdbc:oracle:thin:@localhost:1521:xe", *
1363 //create Prpeareedstaement obj
1364 PreparedStatement ps=con.prepareStatement("select * from StudentAll where sn
136s //set Query paran values
1366 ps.setInt(1,n0);
1367 //execute the Query
1368 ResultSet rs=ps.executeguery();
1369 Hiprocess the ResultSet
1370 Reader reader-null;
3371 f(r next()){
72 readersrs.getcharacterstrean(4);
1373 +
74 I/ereate Writer
1375 Writer writersnew FileWriter(*myResune.txt");
1376 //use Buffer based logic to write CLOB value to Dest file
1377 char buffer[J=new char[2048];
1378 int charsReada0;
B79 while((charsRead-reader.read(buffer))!=-1){
1380 writer.write(buffer,@,charsRead) ;
1381 +
1382
1383 System.out.printIn("“File has been Retrieved");
1384
138s [close jdbc objs
1386 reader .close();
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet Hyd, Ph: 40-23746666, ww.fo.Com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
writer .close();
rs.close();
ps.close();
con.close()5
Wimain
y/felass
CLobRetrievel. jave
package com.nt. jdbc
import java. io.Fileoutputstream;
import java. io. InputStream;
import java. io.OutputStrean;
Amport jave.sql .clob;
import java. sql-connection;
import java.sql.DriverManager;
import java.sql.Preparedstatenent;
import java.sql.Resultset;
import java.util.Scanner;
public class CLobRetrievel {
public static void main(Stringl] args)throws Exception {
//vead inputs
Scanner sc=new scanner(System. in);
Systen.out-printIn(“Enter student no”
int no=sc.nextint()5
//Establish the connection
Class, forane(“oracle. jdbc driver .OracleDriver);
Connection con=DriverManager..getConnection("idbc:oracie:thin:@localhost:1521:xe", “s
[create Prpeareedstaenent obj
Preparedstatenent ps=con.preparestatenent("select * from StudentAl where sno:
/iset Query param values
ps.setznc(1,n0);
//execute the Query
Resultset rs=ps.executeQuery();
[process the ResultSet
lob
javac CsTest1.java
J />java CsTesth
App23 (Application on CallableStatement obj Using Curosor)
-CursorsTest . java.
s*ereate-or replace procedure fetch AllEnpDetails(initchars in varchar, details cut sys_refcursor)as
begin
open details for
select * from emp where ename like initchars;
end;
ir ‘
//CursorcsTest. java
import java.sql.* 5
import java.util.*;
import oracle. jdbc.*; // for OracleTypes class ( this pkg is available in ojbct4.jar file)
public class CursorcsTest
{
public static void main¢ String args[ ] ) throws Exception
{
/I read cond character from key board
Scanner scunew Scanner(System. in);
Systen.out.println("Enter characters (first letters of emp name)");
String cond=sc.next();
cond=cond#"%"
H/create jdbc con obj
lass. forNane( “oracle. jdbc.driver.OracleDriver);
Connection con = Drivertanager.getConnection("jdbc:oracle: thin:@localhost:1521:xe","scott*
Callablestatement cs = con.prepareCall("{call fetch_AllEmpbetails(?,?) }*)
// register out parameter with jdbc types (Oracle corp supplied jdbc types)
cs.registerOutParaneter(2, 0racleTypes -CURSOR) ;
// set value to IN parameter ,
cs. setString(1, cond);
J/ execute pl/sql procudre :
cs.execute() 5
1/ gather result from out paramter
ResultSet rs=(Resultset)cs.getooject(2);
J/display result
while(rs.next())
{
}
I] close jdbc objects
rs. close(
cs.close(
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/nareshit
System.out.printIn(rs.getInt(1)+" “#rs.getString(2)+" “#rs.getString(3)Naresh i Technologies APPLICATIONS By MrNataraj
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1622
1603
1604
1605
1606
1607
1608,
1609
1610
1611
1612
1613
1614
1635
x66
1617
1618
1619
3628
1621
1622
1623,
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639,
1640
1641
1642
1643
1644
1645
1646
1647
1648,
1649
1650
con.close();
App 24) App calling pl/sql function
-csFxTestt Java:
/*create or replace function Fx_Get_EmpDetails(no in number,name out varchar,salary out nunber)retur
desg varchar2(20);
begin
select enane,sal,job into name, salary,desg from emp where empno=no;
return dese;
end;
"
package com.nt. jdbc;
import Java.sql.Callablestatenent ;
import java. sql.Connection;
import Java. sql.DriverManager;
import java.sql.Types;
import java.util-Scanners
public class CsFxTesti {
public static void main(stringl] args)throws Exception {
/icead input value
Scanner sc=new Scanner(Systen.in);
system.out.println( "Enter no:");
Int nozse.nextInt();
/ivegister driver and establish the connection
Class. fortiane “oracle. jdbe.driver .Oracleriver") ;
Connection coneDriverManager..getConnect ion( "jdbe:oracle:thin:@localhost::
Hlprepare query
string qry="{?= call Fx_Get_EnpDetails(?,?,?)}"s
/{create Callablestatement obj
Caliablestatenent cs=con.prepareCall(qry);
//eegister return,OUT parans with JOBC types
cs.registerOutParameter(2,Types. VARCHAR) ;//return param
cs. registerOutParameter(3, Types. VARCHAR) ;//out param
cs.registerOutParameter(4, Types. INTEGER) ;// out param
//set value to IN paran
es.setInt(2,n0);
//call pl/sql function
cs.execute();
[/Gather results from OUT, return paraneters
int salary=cs.getInt(4); //from OUT
String desgucs.getstring(1); //fron return
String name=cs.getString(3); //from OUT
Systen.out.printIn("Nane:" «nanet"desgs"4desge"Salary="ssalary);
[close jébc 0bjs
cs.close();
con.close();
1521
}/wain
Miclass
~CsFxTesti. java~
/ICsFxTest2. java
/* create or replace function Fx_Get_Student_FORDELETION (no in nunber, cnt out nurber)return sys_
as
details sys_refcursor;
begin
open details for
select * from student where sno=no;
"Naresh | Technologies, Opp. Satyam theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit.APPLICATIONS By Mr.Nataraj
1651
1652
1653 F
1654 end;
1655
1656 */
1657 import java.sql.*;
1658 import jave.utii.*;
4659. import oracle. jabe. *;
1668
1661 public class ¢:
1662 {
15
“ROWCOUNT
urn dotad2s;
‘Test
663 public static void main(String args[])throus Exception
1664 4
1665 // read input values from keyboard
4666 Scanner sc=new Scanner(Systen. in);
3667 systen,out.printIn("enter student’ no”);
1668 int nowse.nextInt();
1669
1670 // create jdbc con object
3671 Class. forWane(“oracle. jdbc.driver .oraclebriver");
1672 Connection con-DriverHanager .getConnection("jdbe : oracle: thin:blocalhost:1521:xe","sc
1673
1674 I/eveate jdbc Callablestatenent obj
1675 Callablestatenent cs=con.prepareCall("{?= call FX_GET_STUDENT_FOR_DELETION(?, ?)}")5
1676
4677 // register out,return params with jdbc types f
1678 cs.registerOutParaneter(1,0racletypes.cliRSOR); //return param
1679 cs.registerOutParaneter(3, Types. INTEGER);//out param t
1680
1681 //set values to IN parancters
1682 €s.setInt(2,n0);
1683
1684 J/ call and execute pl/sql function
1685 cs.execute();
1686
3687 // gather results fron return,out parans
1688 ResultSet rs=(ResultSet)cs.getdbject(1); // fron return paran(cursor)
1689 Hiprocess return value result
1690 while(rs.next())
1691 { t
1682 systen.out.printin(ns.getint(1)+" “sns.getstring(2)+" “érs.getString(3));
1693
1694 ,
1695 cs.getint(3); //out param result
1695 2)
1697 System.out.printin(*Record not deleted");
1698 else
1699 system.out.printIn(“Record deleted");
3700 //eose jdbc objs
ye1 rs.close(}s
3702 cs.close();
4703 con.close()s a
1708 Wimain
1705 }//elass
1706 //>javac CsFxtestt.java
1707 //>java CsFxTest1
1708
1709 = oe =naeet = eoeewnes
1710 App26(Using Swings+JD8C) (program using all three Statenent Objects)
ain rocedure in oracle
1712 create or replace procedure FIND_PASS FAIL(ai in nunber,m2 in nunber,m3 in nunber,res out varchar) 2
1713 begin
a4 i#(m1¢35 or m2<35 op m3<35)then
ms resi='fail';
1716 else
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Pi: 040-23746666, wwrw.fo.com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
4717
i718
1718
1726
1721 package com.nt. jdbc;
1722
1723 import java.awt.Color;
1724 import java.awt.FlowLayout;
4725 import java.awt event .ActionEvent;
1726 import java.awt.event ActionListener;
1727 import Java.sql.callablestatenent;
1728 import java. sql.connection;
1729. import java. sql.DriverManager;
1730 inport java. sql.PreparedStatenent;
1731 import java.sql.Resultset;
1732 import java.sql.Statenent;
1733 import java. sql. Types;
1734
1735. import javax. swing. JButton;
1736 import Javax. swing. 3ConboBox;
1737 import javax. swing. JFrame;
1738 import javax.swing. Label;
1738 import javax. swing. TextField;
~-AllStatsTest. Java:
PSEA MTEL een into po ee kw
1780
3781 public class AllstmtsTest extends IFrame implenents ActionListener{ a
3742 private 3Label 1no,1name,Int,ln2,1n3, 1res3 sq
1743 private JTextField tnane, tnt, tn2, tn3, tres; ;
1744 private JButton bdetails,bresult; og
374s private IConboBox tno; i
ams private Connection con;
3747 private Statenent st;
1748 private PreparedStatement ps;
4749 private Callablestatenent cs;
1750 private ResultSet rs1,rs25
1751
1752 Heconstructor
1753 public Allstatstest(){
1754 systen.out.printIn(*"Constructor");
1755 setsize(400,400);
3756 setBackground(Color.cyan);
1737 setLayout (new FlowLayout());
1758 setDefaultClosedperation(JFrame.EXIT_ON_CLOSE);
3759 Hiprpeare and Add comps
3760 Anosnew ILabel ("sno");
et add¢no}
3762 tnosnew 3ConboBox);
1763 add(tno) 5
1764
1765 bdetailsenew JButton("details*);
1766 bdetails. addactionListener(this);
1767 add(bdetails
1768
1769 Inanesnew 3Label("snane");
1778 add(Iname) ; .
vm ‘tnane=new JTextField(10);
wm add(tnane);
73
7 Inienew ILabel ("Harks1")
1775 add(m); :
76 tatsnew ITextField(10);
v7 add(tat);
3778
79 An2enew ILabel (*Marks2");
1780 adé(la2);
1781 ‘tn2-new ITextField(10);
3782 add(tm2);
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 0:Naresh i Technologies APPLICATIONS By Mr.Nataraj
InB-new JLabel (“Marks3");
add(1n3);
‘tn3enew JTextField(19);
add(tm3) 5
bresult=new JButton(*Result");
bresult .addActionListener(this) ;
add(bresult);
Iresenew JLabel(*Result");
add(Ires) 5 -
tres=new JTextField(10);
add(tres);
setVisible(true);
mytnit();
}//constructor
private void nyInit(){
System.out. println(“nyInit()");
tryt
/[register driver
Class. fortiame(“oracle. jdbc.driver Oraclenriver");
[Establish the connection
‘con=DriverHanager.getConnection( "jdbc:oracle: thin:@localhost:1521:xe","scott™, "tiger
/[create Statement obj
stscon.createstatement();
J/exeute logic to get sno values into conbo box
Psiest executeQuery("select sno fron All_student");
ubile(rst.next()){
‘tho.addItem(rs1.getString(1));
W/while
Psi.close();
st.close();
//create Prparedstatenent obj
ps=con.prepareStatenent("select * from All_Student where sno=2");
Hicreate CallableStatenent obj
s=con.prepareCall("{call FIND_PASS_FAIL(?,?,?,?)}")5
cs.registerOutParameter(4, Types .VARCHAR) ;
yitry
catch(Exception ¢){
e.printstackTrace() ;
+
Hénytnit()
@override
public void actionPerformed(ActionEvent ae) {
System.out.println("action Performed");
4 (ae. getSource()=sbdetails){ _
System.out.printIn(“Details btn is clicked");
[Jeet Selected iten fron conbo box
String tsno=(String)tno.getSelecteditem();
int no=Integer.parseInt(tsno);
try
//set value to Preparestatenent obj Query
ps.setInt(1,n0);
Hexecute the Query
rs2eps. executeQuery();
[set values to text boxes
if (rs2.next()){
‘thane. setText(ns2.getstring(2))s
tit. setText(rs2.getstring(3))3
‘Naresh’ Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit1849
1850
est
1852
1853,
1354
1855
1856
1857
1858
1859
1860
1861
1362
1363,
1364
1365
1266
1867
1868
1363,
1878
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1s81
1882
1383,
1384
1885,
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
3980
1901,
1962
1903
1904
1985
1986
1907
1908
1909
1910
1911,
1912
1913,
1914
Naresh i Technologies APPLICATIONS By MrNataraj
‘tnd. setText(rs2.getstring(4)) 5
tm3.setText(es2.getstring(5))3
wie
Witry
catch( Exception e){
e.printStackTeace();
ot
wae
alse
tryf
systen.out.printIn(“Result Btn is clicked");
//read values fron marks text boxes and set then IN paran values
¢s.setInt (1, Integer.parseInt (tmi.getText()));
-€5.Setint(2, Integer.parseInt(tm2.getText()))5
cs.setInt (3, Integer.parseInt(tn3.getText()))3
/1call pl/sql procedure
cs.execute();
//eather result from OUT param and set to text box
tres.setText (cs. getString(4));
>
catch(Exception e){
e.printstackTrace();
;
V/else
}factionPerformed(-)
public Static void main(stringl] args) {
systen.out.printIn("main(-)");
‘AllstatsTest statsenew Allstmtstest();
App27( Scrollable Resultset obj)
~ScrollTest .java
//Scrollabletest. java
import java.sql.*3
public class ScrollableTest
{
public static void main(String args[])throws Exception
{
//oad jdbc driver class,create jdbc con obj
Class. forName( "oracle. jdbc.driver .Oracledriver");
Connection coneDriverManager.getConnection("“jdbc:oracle:thin:@localhost:1521:xe", "sc
// create Jdbc Statement obj with type,mode values
‘Statement ,st=con.createStatement (ResultSet. TYPE_SCROLL_SENSITIVE, ResultSet .CONCUR_UPI
U1 create Scrollable ResultSet obj
Resultset rsest.executeQuery("select * from student");
1/ display records (top-bottom)
System.out.printIn("Top-to bottom");
while(rs.next())
Systen.out.printIn(rs.getInt(1)+" “#rs.getString(2)+" "#rs.getstring(3));
Wiwhile
JI display records (botten-top)
System. out .printIn("Botton-Tap") ;
rs.afterLast()5
khile(rs.previous())
‘Naresh’ Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/noreshit 32:
BSSEEEREEES
49,
oeNaresh i Technologies APPLICATIONS By MrNataraj
t
System.out.println(rs.getInt(1)+" “srs.getString(2)+""#rs:
Wiwbite . Ee)
i {display records randomly
rs.first(); //gives First record
system.out. printIn(rs.getRow()+
-)"ers.getInt(1)+" “4rs. getString(2)+"
rs.last(); //gives Last record
systen.out.printIn(rs.getRow()+"--->"srs.getint(i)+" “ers. getString(2)+"
rs.relative(-2); //gives Last but 3 :
systen.out.printIn(rs.getRow()+"--->"srs.getInt(1)+" "ars getString(2)+"
rs.absolute(4); //gives 4th record
systen.out.printla(rs.gotRoa(j+"--~>"4rs.getine(i)+" “wns getstring(2)+*
rs.absolute(-2); //gives last but 1 record
systen.out.printin(rs.getRow()+
rs.relative(1)} //gives last record
systen.out.printIn(rs. getRow( )+"
//chose jdbc objs
rs.close();
ps.close()}
con.close(}
App28 (Using Scrollable ResultSet object)
ScrellFrane. java
etString(3))3
“Hrs gets)
“ers. gets
‘ers .gets:
‘srs gets
>'ars.getInt(1)+" “ers.getString(2)+" “+rs.getString(3)
rs.getInt(1)+" “4rs.getString(2)*" “4rs.getString(3)
/*perform first, last,previous and next navigation buttons using scrollable Resultset*/
import java.sql.*;
import java.awt.*}
import java.awt.event.*
public class ScrollFrane extends JFrame implements ActionListener
{
private JTextField tsno, tsna, tsadd;
private JLabel Ino,1na,ladd;
private JButton bfirst, blast, bnext, bprevious;
private Connection con=null;
private Statement st-null;
private ResultSet rsenullj
ScrollFrame()
{
system. out.printIn ("constructor");
setLayout (new FlowLayout());
setBackground(Color.green);
setSize(400,200);
//add. comps to Frame window
‘no=new JLabel ("SNO") ;
add(1nd) 5
tsnd = new ‘ITextField(2@);
add(tsno) 5
Anasnew JLabel (“NAME”) ;
‘add(Ina);
‘tsna = new ITextField(20);
add(tsna);
Ladd=new JLabel ("ADDRESS");
add(ladd) 5
tsadd = new JTextField(20);
add(tsadd);
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 04023746666, www fb.com/nareshit
7Naresh i Technologies APPLICATIONS By Mr.Nataraj
bfirst = new JButton("First");
add(bfirst);
bfinst .addactionListener(this);
blast =new 3Button("Last");
add(blast);
blast .addActionListener(this);
bprevious = new 38utton("previous");
add(bprevious);
bprevious.addActionL istener(this);
bnext = new JButton("next");
add(bnext);
bnext.addActionListener(this);
. setVisible( true) ;
'_ setdefaul tCloseOperat-ion(3FRANE.EXIT_ON_CLOSE);
makeconnection();
?
private void makeConnection()
{
try
{
system.out.println( "nakeConnection()");
//register jdbc driver
Class. fortiane(“oracle. jdbc.driver.Oraclebriver");
/lestblish the connection
con = Drivertanager.getConnect ion(" jdbc:oracle:thin:@localhost:1521:xe",
//create Statenient obj
st = ¢on.createStatenent (ResultSet. TYPE_SCROLL_ SENSITIVE, ResultSet .CONCUR_RE,
// create Scrollable Resultset
rs = st. executeQuery("select * from student");
systen.out.printin("scrollble resultset object 1s ready");
"scott", "tiger")
}
catch(Exception ce)
{
ce.printstacktrace();
}
}/wake connection
public void actionPerformed(Actionévent ae)
{
systen.out.printa(“actionPerformed()");
boolean found=false;
try
{
system.out .printIn(ae.getActionCommand());
if(ae.getSource()==bfirst) //uhen first btn is clicked
{
rs.first()5
found=true;
t
else if(ae.getSource()sblast) //when last btn is clicked
{
rs.last(); .
found=true;
}
else if(ae.getSource()exbnext) //when last btn is clicked
Af(Irs.istast())
{
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 04%
746666, wwvifb.com/nareshitNaresh i Technologies APPLICATIONS By Mr.Nataraj
rs.next();
found-true;
}
+
else it(ae. getsource(
previous) //uhen previous btn is clicked
if(Irs.isFirst())
rs.previous();
found=true;
if (found)
{
tsno. setText(rs.getString(1));
tsna.setText(rs.getString(2));
tsadd.setText(rs.getstring(3));
?
Yeatch(Exception e)
{
e.printStackTrace();
>
}/actionPerformed
public static void main(String args[])
{
systen.out.printIn(“main method");
new Scrollframe();
‘App29(Progran on SensitiveResultset Object)
os -
SensitiveTest .java-
/1 prg to read data from Ds table
import java.sql.*5
public class SensitiveTest
{
public static void main(String args[])throus Exception
{
Hregister jdbe driver and establish the connection
Class. forNane( “oracle. jdbc.driver .Oraclebriver"); i
Connection consOriverManager. getConnection("jdbe:onacle: thin:@localhost:1522:xe",
/Icreate Scrollable and Sensitive ResultSet obj
Statement st=con.createStatement (ResultSet. TYPE_SCROLL_SENSITIVE ResultSet .cONCUR_U
ResultSet rs=st-executequery("select sno,sname,sadd from student");
//logic to demonistrate sensitive behaviour me
int cnte1;
while(rs.next())
rs.refreshiow();
system.out.printla(rs.getString(1)+" "trs.getString(2)#" “ers.getString(?
if(ente=2)
Thread. sleep(408e@); //modify records from SQL prompt
centees
While
/[elose jdbc objs
rs.close();
st.close();
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwwfb.com/nareshit 55:RIE
Naresh i Technologies APPLICATIONS By Mr.Nataraj
= con. close();
Wimain
}felass
2143
214
2aas
2116
2117
218
2119
2120
224
2122
2123
224
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
mal
232
2243
2144
2145,
2146
2147
2148
2149
2158
2151
2152
2153,
2154
2155
2156
2187
2158
2159
2160
2161
2162
2163,
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173,
2174
2175
2176
2177
2378
* app30( prg on Updatable Resultset)
UndatableTest. java
Amport java.sql.*;
public class UpdatableTest
public static void main(String args{])throws Exception
{
[ivegister jdbc driver and establish the connection
Class. forNane( “oracle. jdbc driver oracleDriver") ;
Connection consDrivertianager. getConnect ion("{dbc:oracle: thin:@localhost :1521:xe", "se:
// create jdbc Statement obj, and create UpdatableResultset obj
‘Statement st=con.createStatenent (ResultSet. TYPE_SCROLL_SENSITIVE, ResultSet .CONCUR_UPI
ResultSet rs=st.executeQuery(*select sno,snane,sadd from student");
/*system.out.println(“updates the 4th record");
rs.absolute(4);
Ps.updateString(2, “bab
Ps.updateRow();*/
system.out.printIn("Inserting new row");
rs.noveToInsertRow(); //creates an eapty record in ResultSet obj
rs.updateInt (1,131);
rs.updateString(2, "keyboard");
rs.updateInt (3,57);
rs_insertRow()}
/* System.out.printIn( “deleting 2 th row");
Ps.absolute(2);
rs.deleteRow(); */
rs.close();
st.close();
con.close(};
Wimain
V/class
App3i(To interact with Mysql DB s/w)
-MysSqlSelectTest. java-
import java.sql.*;
import java.util.*;
import java.io.*;
public class HySqlselectTest
t
public static’ void inain(String args[])threns Exception
{
[register jdbc driver and establish the connection
//Ciass.forNane(“org.gjt .mn.nysql .Oriver"); (or)
Class. forNane("con.mysqi. jdbc Driver");
[establish the connection
Connection con-Driverlanager.getConnection("jdbc:mysql:///mydb1",
/[Connection con«DriverManager .getConnection("jdb
1/ create Staenent obj
Statement st=con.createstatenent();
1/ execute the query
ResultSet rsest .executequery("select * from product");
white(rs.next())
"Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit,
oot", “root");
sql: //localhost :3306/aydb1","nNaresh i Technologies APPLICATIONS By Me.Nataraj
{
}
//close all jdbc stream objects
rs.close();
st.close();
con.close();
imain
Hiclass
System.out.printin(rs.getInt(1)+" “srs. getString(2)+" “+rs.getSteing(3))
‘App32. (Interacting with Excel as 08 s/w)
U/éxceliest Java
package com.nt. jdbc;
import java.sql.*;
public class ExcelTest {
public static void main(String[] args)throws Exception {
J/vegister jdbd driver
Class . forNane( "sun. jdbc odbc. 3dbcOdbeDriver") ;
[Establish the connection
Connection con=DriverManager. getConnection("
/* —— [/ereate Staement obj
Statement st-con.createstatenent();
7/ send and execute SQL Query in Db s/w
ResultSet rs=st.executeQuery("select * from {Sheeti$]");
// Process the ResultSet
while(rs.next()){
Systen-out.peintln(rs.getInt(1)+" “ars.getString(2)+" “#ns.getString(3))s
vy 5
Preparedstatenent ps=con.prepareStatement("insert into [sheet1$] values(?,?,?)")s
ps.setint (1,360);
ps. setString(2,ramesh");
Ps. setstring(3,""indore");
int result=ps .executeUpdate();
Systen.out.printin( result+" no.of records are inserted");
idbc:odbe:x1sdsn");
” Helose jdbc objs
: rs.close()
st.close()
con.close(}; */
‘App33) Interacting with csv File
TxtTest. java:
package com.nt.jdbes
Anport java.sql.Connection;
import java.sql.OriverManager;
import java.sql-Resultset;
import java.sql.Statement;
public class TextTest {
public static void main(string{] args)throws Exception {
Ufvegister jdbc driver
Class. forName(" sun. jdbc -odbe. JdbcOdbcDriver");
//Establish the connection
Connection con=Orivertianager.getConnection("jddc:odbe:txtdsn*);
J/create Statement obj
Statement st=con.createStatement();
“Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www [b.Com/nareshit2245)
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2268
2261
2262
2263
2264
2265
2266
2267
2268
2269
2278
2271
272
273
274
2275
2276
27
2278
2279
2280
2281
2282
2283
2284
285
2286
2287
2288
2289
2298
2291
2292
2293
2298
2295
2296
2297
2298
2299
2308
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
Naresh i Technologies APPLICATIONS By MrNataraj
7/send and execute SQL query in Db s/w
Resultset rs=st.executeguery(*select * from files.csv")}
//process the ResultSet
while(rs.next()){
Systen.out.printIn(rs.getint(3)4" “srs. getsering(2)+" “ers. getString(3))5
>
I close jdbc objs
rs.close();
st close();
con.close();
Vimain
yiclass
App34)prg to read data from Excel Sheet and to insert into oracle D8 table)
Excel Te eracle.java-
import java.sql.*;
Public class ExcelToOracle
{
public static void main(string args{])throws Exception
iz
Connection excelcon=nu}l, orac
Statement st=null;
PreparedStatenent. ps
Resultset rs=null;
dj;
21;
Afvegister jdbc drivers
Class. forName(” sun.jddc-odbc. JdbcodbcDriver) 5
Class. forName( "oracle. jdbc «driver .GracleDriver”) ;
Systen-out.printIn("Drivers Loaded");
J/establish the connections
‘excelcon=Drivertanager .getConnection(" jdbe:odbe:x1sdsn")
oracon-DriverManager .getConnection( "idbc:oracle: thin: @localhost:1521:xe", "scott","t
system.out.printin("connections established");
/create Statenent objs
steexcelcon.createStatenent()3
pseoracon.prepareStatenent(*insert into student values(?,?,?)*);
systen.out printin("statengnt prepared");
J/get records from excel sheet
rs=st.executequery(*select * fron {student$]");
while(rs.next())
Iivead each record from excel sheet
int no=rs.getInt (1);
String na=rs.getString(2);
String adders. getstring(3);
-Minsert each record into oracle db table
ps.setInt(1,n0);
ps.setstring(2,na)
ps.setstring(3,add);
ps.executeUpdate();
Miwhile
Systen-out.printin(*oata has been copied");
J/ciose jdbc objs
rs.close()3
st.close();
‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fo.com/nareshit :358::
(STR Rr NA RE ROUNENS n nan al
instalee
2311
2312
2313
2314
2315
2316
2317
2318
2319
* 9320
2321
Naresh i Technologies APPLICATIONS By Mr.Nataraj
ps.close();
oracon.close();
excelcon.close();
Wimain
yielass
‘App35)Program to read Metabata of the Database)
J[patabaseMetadata program
import java.io.*;
import java.sql.*;
public class D8cap
{
public static void main(string args{])throws Exception
IIvegister jdbc driver and establish the connection
Class. forNane( “oracle. jdoc.driver.OracleDriver");
Connection con=DriverManager. getConnection(* jdbc :oracle:thin:@localhost:1521:xe", “scott”, "ti,
//get Metadata
DatabaseMetaData dbmd =con.getetadata();
System.out.printlo(“class that implements vatabaseMetaData(i) is"+dbad.getel
systen.out.printIn(“database name “+dbnd. getDatabaseProductNiane()) 5
systen.out-printin ‘database version, “edbed getDatabase?roductVersion());
systen.out.printInt"jdbe driver version “+dbnd.getDriverVersion());
systen.out.printin("sql key words = “+dbnd.getSOLKeywords())
systen.out.printIn(“nuneric functions “+dbnd.getNumericFunctions());
systen.out.printn("String Functions “+dbnd.getStringFunctions());
systen.out .printIn("system Functions"+dbnd. getSystenFunctions());
systen.out printin("Search String Escape"+dbnd. getSearchStringéscape());
systen.out.printIn(” supportsStoredProcedures = “#dbnd.supportsStoredProcedures());
systen.out.printIn(” gethaxRowSize = "sdbmd.getMaxRowSize());
systen.out.printin(™ getMaxStatementLength = “+dbnd.getMaxStatementLength());
Systen.out.printIn(“get Max tables in 2 select query="tdond. getMaxTablesinSelect())3
systen.out.printIn(“get Max Length of Table Nane="+dond. getMaxTableNameLength())3
systen.out.printIn("jdbc api version is"+dbad.getJ08cMajorVersion()+" . “+dbmd.getIDBCKinor¥
‘App36 (Application on ResultsetMetaData to print table data along with co2 names)
-RenSelectTest.java-
import java.sql.
import java.util.*;
import java.io.*;
public Class RsmSelectTest :
{ —
public static void main(String args[])throws Exception
{
Class. forNane( “oracle. jdbc.driver .OracleDriver");
Connection con-Drivertianager .getConnection("jdbc:oracle:thin:@localhost:1521:x6",*s
// create Staenent obj
Statement st=con.createStatenent();
71 execute the query
ResultSet rs=st.executeQuery("select * from student");
/iget ResultSetMetadata obj
ResultSetMetadata rsnd=rs.getMetadata();
11 get col count
int cat=rsnd.getColunncount();
//print col names
‘Opp. Satyam Theatre, Ameerpet, Hya, Ph: 040-23746666, www.fb.com/nareshit
‘Naresh Technologies,Naresh i Technologies APPLICATIONS. By MrNataraj a
2377 for(int tye) j
2378 ‘ E
2379 System. out. print(rsmd.getColumnLabel(i)+"\t\t\t");
2380 Witer
2381 system. out. println();
2382 //print col vlaues
2383 while(rs-next())
2384
2385 for(int is0;icent;-+44)
2386 { i
2387 System.out.print(rs.getString(i)+"\t\t\t"
2388 }/for
2389 System.out.printin();
2390 Wiubide j
2391 j
2392 J/elose all jdbc stream objects i
2393 rs.close()} j
2394 st.close(); 4
2395 con.close(); i
2396 }/nain
2397 }//class
2398
2399 a —
2408 App37(Program using ParaneterMetaData)
2401
2402 - PupTest. java
2403 import java.sal.*;
2404
2405 public class PxoTest {
2406,
2407 public static void main(Java.lang.string[] args) throws Exception
2408, {
2409 Class. forNane( "sun. jdbc odbc. JdbcOdbeDriver");
2410 Connection con«briverManager .getConnection("jdoc:odbc:mysqldsn”, "root", “root
2011
2412
2413, PreparedStatement ps = con.prepareStatenent ("insert into student values(?, ?, 2)");
2414
2035 ParameterMetaData pmdeps.getParanetertetadata();
2416
2417 System.out.print1n("impl class name of ParaneterMetaData(i)"+pnd.getClass().getName(
2a18
2419 int cntepnd.getParaneterCount();
2420
2021 for (int i ist) {
2422 System.out.printIn("Paraneter number “ + i);
2423,
2424 system.out.printIn(" Mode is * + pnd.getParametertode(i));
2425 systen.out.printin(" Type is + pnd.getParaneterType(i));
2426 System.out.printIn(" Type nane is “ + pnd.getParameterTypeName(i));
2427 Systen.outprintIn(" Precision is * + pnd.getPrecision(i));
2428 System.out.printIn(" Scale ig " + prd.getScale(i));
2429 System.out .printIn(" Nullable? 1s " + pnd. isNullable(i));
2430 system.cut.printin(" Signed? is " + pid.isSigned(i));
2431}
2432 +}
2433}
2034
2435 =
2436 App38(program on jdbc rowset )
2437 sean
2438 Rew. java~
2439 package con.nt. jdbc;
2449 import java. sql.*;
2441 import javax.sql.*;
2442 _ import oracle. jdbc. rowset.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies APPLICATIONS By Mr.Nataraj
2443)
2484
2445,
2446
2447
2448
2449
2458
2054
2452
2453
2454
2855
2056
2857
2058
2459
2460
2061
2462
2463
public class Row
{
public static void main (String (Jargs)
* ey
{
HIereate Rousset obj
RonSet jrowset = new OracleJOBCRowset();
//set jdbc properties
Srowset.setUrl(“jdbe:oracle: thin:@localhost:1521:xe");
Jrowset.setUsername(*scott");
jrowset.setPassword(“tiger");
Jrowset.setConnand("select enpno from enp*) ;
jrowset -execute();
Systen.out.print1n("conmand executed");
/ipracess the Rowset
while (Jrowset.next())
{
System.out.println (jrowset.getInt(1))5
t
jrowset.close();
}
catch(Exception ee)
{
System.out.printIn(ee.toString());
‘App39) CachedRowset
-Rew2. java.
package con.nt. jdbc;
import java-sqi.*;
import Javax.sql.*;
public class Row2
{
public static void main (String [Jargs)throws Exception
‘
I/create Rouset obj
oracle. jdbc.rouset .OracleCachedRowset crowset= new oracle. jubc.rowset.OraclecachedRowset();
I/sct jdbc properties
crowset .setUrl("jdoe:oracle: thin :@localhost:1521:xe");
crowset .setUsernane ("scott");
crowset .setPassword(“tiger");
crowset.setConmand("select * from student");
crowset .execute();//executes Query
Systen.out.printin("query executed");
Hiprocess the Rowset
while (crouset.next())
i
systen.out.println (crowset.getInt(1)+" “#crowset .getString(2)+" “scrowset.getstring(3) )
' =
crowset.setReadOnly( false);
crowset absoluter(2)3
crowset.updatestring(3,"new delhi");
crowset .updateRow();
crogset -acceptchanges();
[close Rowset
crowset.close();
} Swain
VielassNaresh i Technologies APPLICATIONS By Mr.Nataraj
2509
2510
2511
2512
2513,
2518
2515,
2516
2517
2538
2519
2520
2521
2522
2523
2524
2525,
2526
2527
2528
2529
2530
2531,
2532
2533
2534
2535,
2536
2537
2538
2539
2540
2541
2542
2543,
2544
2545
2546
2547
2548,
2549
2550
2551
2552,
2553
2554
2555
2556
2557
2558
2559,
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2872
2573
2574
Row3. java~
package com.nt. jdbcs
import java.io.File;
import java.io.FileWriter;
impart java.io. Stringuiriter;
import javax.sql.rowset.NebRowset3
import oracle. jdbc. rowset.OracleWebRowSet;
public class Row’ {
public static void main(string{] args) {
ay
t
UIcreate WebRowset obj
OracleWebRowSet webRS= new CracleifebRowset (:
J[set jdbc properties
webRS. setUsername("scott");
webRS. setPassword("tiger");
webRS. setUrl ("jdbe: oracle: thin:@localhost:1521::xe"
webRS. setCommand("SELECT * from employee");
/Jexecute the query
webRS.execute();
{[create or locate file
File, nyFile-new File("c:/enployee1.xml");
Fileliriter fw = new FileWriter(myFile);
systen.out.printIn("hriting db data to file " + myFile.getAbsolutePath());
webRS.writeXml (fu); // writes the records of Rowset to file
// convert xml to a String object for display purpose
Stringhriter sw = new Stringwriter();
webRS.writexal (sw) 5
system.out. print1n(sw.tostring());
fa Flush);
fu.close();
}eatch(Exception e)
e.printStackTrace();
App4o) JoinRowset
Ron. java
package com.nt. jdbc;
import oracle. jdbc.rowset.OracleCachedRowset;
Amport oracle. jdbc.rowset -OracleJoinfowset
public class Rowd{
public static void main(String args{]) {
try {
1/Cached RowSet1
OracleCachedRowSet crst
erst, setUrl ("jdbc:oracle
crsi. setUsername("scott”)3
crs. setPassword(“tiger")3
crsi.setConmand(“select enpno,ename,deptno fron emp");
erst. execute();
' ersi.setMatchColumn(3) ;
new OracleCachedRowset();
thin :@localhost:1521:xe")
J[Cached Rowset2 .
OracleCachedRowSet_crs2 = new OracleCachedRowset()
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph; 040-23746666, www.fb.com/nareshit 762:Naresh i Technologies APPLICATIONS By Mr.Nataraj
crs2. setUrl( "jube:oracle;thin:@localhost:1521:xe");
crs2. setUsernane("scott");
crs2.setPassword( tiger");
crs2.setComand("select * from dept");
ers2.execute();
crs2. setHatehColumn(1) ;
//kdd multiple RowSets to JoinRowset
OracleJoinRowSet joinkS = new OracleJoinRowSet() ;
JoinkS.addRowSet (erst) ;
Joinks. addRonset (crs?) $
/[Process JoinRowset
hile "(JoinRs.next()) {
Systen.cut.println(joinRS.getString(1)+" “+joinRS.getstring(2)+" “+JoinRS.getString(3)+"
=
} catch(Exception e) {
e.printStackTrace() 5
$2598 App 41) FilteredRowset
package com.nt. jdbc;
import java.sqi-SQLException;
import javax.sql.RowSet;
import Javax.sql.rouset.CachedRowset
Amport javax.sql-ronset.Predicate;
import oracle. jdbc. rowset.OracleFilteredRowset;
class Filter1 implenents Predicate {
private String colName;
public Filtert(String colName) {
‘this.colNane = colName;
+
public boolean evaluate(Rowset rs) {
try {
CachedRowSet crs = (CachedRowSet) rs; //get Each record of ResultSet as CachedRowset
String object = crs.getString(colNane);
Af (object != null &8 (object.charat(@) == ‘A’ || object.charat(e)
return true;
} else { :
return false;
wy
}
} catch (Exception e) { a
return false;
>
>
public boolean evaluate(Object argo, int argi) throws SQLException { 3
return false;
}
public boolean evaluate(Object arg, String argi) throws SQLException {
return false;
}
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
2641,
2642
2643,
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653,
2654
2655,
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2696
2691
2682
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
st.addBatch(“delete from student where sno=34")
public class Row5 {
public static void main(String[] args) throws Exception {
OracleFilteredRowSet frs = new OracleFilteredRowSet();
frs.setUsername("scott");
fs. setPassword("tige
frs.setUrl("idbczoracle!
frs.setconnand( "select
//dpply Filter
frs.setFilter(new Filtert(“enane"));
Frs.execute();
while (Frs.next()) {
system,out.printIn(frs.getInt(1)+" “sfrs.getString(2)+" “sfrs. getString(3));
hin:@locathost:1521:x%
‘from emp");
d5
}
‘App42) BatchProcessing/Updataion)
BatchPrecess. java~
package com.nt.jdbes
import java.sql-*5
public class BatchProcess
{
public static void main(String args[])throws Exception
{
//oad jdbc driver and establish the connection
Class. forNane( “oracle. jdbc .driver.Oracledriver"
Connection consDriverManager..getConnection("jdbc:oracle:thin:@localhost:1521:xe", "sc
//disable the autoconmit node
con, setAutoConmit (False);
//ereate Statenent obj
Statement stzcon.createStatenent();
// add queries to batch
staddBatch(“update student set snane='chinnai' where sno=107@");
st.addgatch("insert into student values(169, ‘ccc',,'muak;")");
JI execute the batch
int result[ Jest executeBatch();
Mprocess the results
int sum=o;
for(int i=;icresult.length;++i)
{
t
Systen.out. printIn
sun-sun+result[i];
no.of records that are effected"+sum);
st.close();
con. close();
Wimain
yjelass
App43( Transcation Management)
java
1 TrtigntTest java
package con.nt.jdb
import java.sql.*}
import Java.util.*;
public class TxMgmtTest
{
public static void main(String args[])
{
Connection consnull;
‘Naresh (Technofogies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshitNaresh i Technologies APPLICATIONS By MrNataraj
——
‘Statement st=null;
try
{
J/read input value from keyboard
Scanner scenew Scanner(System. in);
system.out.printIn(“Enter sre a/c no:");
int srcacno=sc.nextInt();
Systen.out.println("Enter Dest a/c no:");
int destacno=sc.nextInt()}
Systen.out.printIn("Enter Ant to transfer:
int amt=sc.nextInt();
11 create jdbe con obj
Class. forName( “oracle. jdbc.driver OracleDriver");
con=Drivertanager.getconnection("dbe:oracle: thinz@locelhost:152u:x8", "scott
//disable auto commt mode
con. setAutoConmit (false); //begins Tx
// create jdbc statement object
st=con,createStatement(); {
// add queries of transfertoney operation to batch processing
/Iquery for withdraw operation
st.addBatch("update jdbc_account set balance-balance-"samt+" where acno="#sr
ZIquery for deposite operation
st-addBatch(“update jdbc_account set balance-balance+"+ant+" where acno="+de
// execute the queries of batch
int res[]=st.executeBatch();
/Iurite the code of Tx mgmt
boolean flag=true;
for(int ixosdcres.lengths++4)
if(res[i]==0) // if any element value is @
flagefalse;
break;
}
}
//commit or rollback the Tx :
Af (flagesfalse)
{
con.rollback();
system.out printIn("Tx is rolledback(money not transffered)");
}
else .
“
con. conmit(); Serra
System.out.print1n("Tx is conmitted(Money transffered)")3
}
/1elose jdbc objs
st.close();
con.close();
catch(Exception e)
{
"Naresh | Technologies, Opp. Satyam Theatre, Ameepet, Hyd, Ph 040-23746666, wuw,fo.com/nareshit 65:
try
{
)
con.rollback();Naresh i Technologies APPLICATIONS, By Mr.Nataraj
2773 catch (Exception e1){el.printstackTrace(); }
2774 3 [eatch
2775 Wimain
2776 }/class
2777 j/>javac TxMgntTest. java
2778 //>java TxMgntTest
2778 — =
2788 Appa (Batch Processing by using PreparedStatenent obj)
2781
2782 -psBatchTest. java
273 //pspatchTest.java
2784 package com.nt.jdbes
2785 import java.sql.*;
2786 public class PsbatchTest
2787 {
2788 public static void main(String args{])throws Exception
2789 ‘
2798 11 create jdbc con obj
2791 Class. forNane(“oracle. jdbc.driver.oracleDriver");
2792 Connection con=DriverManager.getConnection(“jdbc:oracle: thin:@localhost:1521:xe", “sc:
2793
2734 //create Preparedstatenent obj
2795 PreparedStatenent ps=con.prepareStatenent("insert into student values(?,?,?)")
2796 Sfadd param values to batch
2797 ps.setInt (1,111);
2798 ps.setString(2,"raja");
2798 ps.setstring(3, "hyd");
2800 ps.addBatch(); //add Ist set param values to batch
2801
2802 ps. setInt (1, 222:
2803 ps.setString(2,
2804 ps.setstring(3,
2805 ps.addBatch();//add 2nd set param values to batch
2806
2807 ps.setint (1,333);
2808 ps.setString(2,“rakesh");
2803, ps.setString(3, "hyd2")5
2810 Ps.addBatch();//add 3rd set param values to batch
2811
2812 // exeute the Query
2813 Ant res{ ]eps-executeBatch();
2814
2815 /Iproces the result
2816 Ant ent=83
2817 for(int i=@;icres.length;++i)
2818 {
2819 entecnteres[i];
2820 }
2821
2822 system.out.printin(“no.of records that inserted: "+ent);
2823
2824 //close jdbc objs
2825 ps-close()
2826 con.close()s
2827 fwain
2828 * }//class
2829
2830 sawnee
2831 App4S(progran to make JBC Application Flexible)
2832
2833
2834 properties file
* 2835. driversoracle. jdbc. driver .OracleDriver
2836 url=idbc:oracle:oci8:@xe
2837 _userescott
2838 password
paDetails properties
‘iger
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies _ APPLICATIONS By Mr.Nataraj
FlexiblesbECTest. java
//FlexibleIDaCTest. java
package com.nt. jdbc;
import java. sql."
import java.i0.*;
import java.util.*
public class Flextest
(
public static void main(String!) args)throws Exception
{
[Mocate properties file
FileInputStrean Fissnew FileTnputStrean("babetails.properties")5
{Head the datz of properties file .to Properties class obj
Properties panew Pronerties();
p.load (Fis);
11 get Jcbc details Fron Properties class obf
String step. get?roperty(*driver");
String s2=p.get?ronerty(*unl");
String s3=p.get®roverty(*user");
String s4=p.getPronerty(*password
IIweite jdbc code
Class. forName(s1);
Connection con=DriverManager.getconnection(s2,s3,54);
Statement st«con.createStatenent()}
ResultSet rsust.executequery("select * from student “);
while(rs.next())
{
‘Systen.out.printIn(rs.getString(1)+" “srs.getString(2)+" “+rs.getstring(3
,
rs.close();
st.close();
con.close();
Wémain
iclass
‘App46 (on Drivertanaged Idbc Conn Pooling )(Client Side com pool)
- - ConnPoolTest..java~
//ConnPooltest.java (works with DriverManaged Jdbc con pool)
package com.nt. jdbc;
Inport java.sql.*5
inport oracle.jdbe.pool.*; // (for OracleConnectionPoolDataSource (c))
public class ConnboolTest
{
public static void main(String args{])throws Exception
t
// create jdbc datasource obj representing an enpty driver managed con pool for oracle
OracleConnectionPoolbataSource ds = new OracleConnectionPoolDatasource();
// give details to create jdbc con objects in the above empty can pool
ds.setOrivertype ("thin");
ds. setServerNane (“localhost”);
ds.setPortNunber (1521)}
ds.setServiceName ("xe");
ds.setUser (“scott
ds.setPassword("tiger"); //-->now jdbc con pool is ready with jabe con objs
/1 get one jdbc con obj from jdbc con pool through DataSource obj
Connection consds.getConnection{);
J/ write jdbe persistance logic
Statement st=con,createStatement();
ResultSet rsest.executeguery("select * from student’
while(rs.next())
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit2905)
2906
2907
2968
2909
2910
2911,
2912
2913,
2914
2915
2916
2917
2938
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933,
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943,
2944
2945
2986,
2947
2948
2949
2958
2951
2952
2953
2954
2955
2956
2957
2958
2959
2360
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
Naresh i Technologies APPLICATIONS By MrNataraj,
{
)
Helose jade objects
rs.close();
st.close();
con.close(); {releases con obj back to 2dbe Con pool
Winain
Miclass
H/asd ojdoci4.jar file to classpath
//yJavac ConnPoottest. java
//>Jave ConnPooltest
systen.out.erintin(rs.getint(1)#" “ees.getString(2)+" *ers.getstring(2))5
Appa7(SavePoint )
SavePointTest. java
//SavePointTest. java
package ¢om.nt. jdbc;
import java. sql-*;
public Class SavePointTest
{
public static void main(String args[])throws Exception
{
/Jregister jdbc driver and establish the connection
lass. fortiame( “oracle. jdbc.driver .OrackeDriver");
Connection con=DriverManager .getConnection(" jds<:oracle: thin:@localhost:1521:xe", "sc:
Hcreate statment obj
Statement st = con.createstatement();
11 Begin Tx
con. setAutoConnit (Fase) ;
//query (outside the save point area)
st.executeUpdate("insert into student values(567, ‘xy2", 'hyd1')");
if create Waned Save Point (“p
Savepoint sp=con.setSavepoint ("pi");
//query2< in save point area)
st.executeUpdate(“update student set sadd='new delhi’ where sno=111");
//roLlaback upto savepoint (P1)
con.rollback(sp);
11 commit 1%
con conmit(); //end of the Tx
//query1 will be commited but query2 will be rolled back
{Ibecoz the query2 is there in savepoint area. .(p1)
Wimain
Viclass
//>}avac SavePointTest. java
//>java SavePointTest
App48 (interacting with Postgres SQl DB s/w)
//PostgreSQlapp. java
package con.nt. jdbc;
import java.sql.*5
public class Postgresotapp
{
public static void main(String args{])throus Exception
t
[ivegister jdbe driver with Drivertanager Service
Class. forName(“org.postgresal .Driver");
//establish the connection
//Connection con=DriverManager.getConnection("jdbc:postgresql:nydbi" , "postgres", "root");
Hor
Connectioncon=Driveranager . getConnection( "jdbc:
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit
jostgresql: //localhost:5432/nydb1” , “postgres”Naresh i Technologies APPLICATIONS __8y MrNataraj
1/ create jdbc statement obj
Statenent stecon.createstatement();
7/ send and exacute SQL query
ResultSet rs=st.evecuteQuery("select * from product");
Iprocess the jdbc KesuitSet obj
uhile(rs.next())
Systen.out.printIn(rs.getInt(1)+"
rs.getString(2)+" “Hs. getFloat(3));
7
I/ close jdbc objects
rs.close();
st.close();
con.close();
y/main
Viclass
/[>javac Postgresgtapp. java
//>java PostgresoLapp
App49( Example Application Type3 IDBc driver)
Type3Testi. java
[ypestest.java
package com.nt. jdbc;
import java.sqi.*;
class Type3Testt
{
Public static void main(string{} args) throws Exception
Hvegister type jdbe driver
Class. forNane("1ds.sql.1DSDriver");
J/Establish the connection
7/Connection con = DriverManager.getConnection(* jdbc: ids :// localhost :12/conn?dsn=or
Connection con = DriverManager.getConnection(" jdbc: ids://localhost :12/conn?dsn="accd
I/ereate jdbc Staterent obj
Statement. st = con.createStatenent();
7/ execute the SQL Query
ResultSet rsest.executeQuery("Select * from student”);
J/process the ResultSet obj
while(rs.next())
{
System.out.printin(rs.getInt(1)#" “#rs.getString(2)+" “4rs.getstringys));
}
T/aose jdbc objs
rs.close();
st close();
con.close();
y ’
‘App5® (Application on Types JDBC Driver)
TypesTest. java-
/TTypestest. java
Package com.nt.jdbc;
import java.sqi-*3
public class TypeSTest
{public static void main(String[] args)throws Exception (
//oading jdbc driver class is optional here
7/Class .forNane( “con, ddtek. jdbe.oracle.OracleDriver");
// Establish the Connection
Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 68:Naresh i Technologies APPLICATIONS By MrNataraj
3037
3038
3039
3040
3041
3042
3043
3eaa
3045,
3046
3047
3048
3049
3050
3052
3052
3053,
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063,
3064
3065,
3066
3067
3068
3069
3070
3071,
3072
3073
3074
3075,
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3302
String url = “}dbe:datadirect :oracle://localhost 1521; ServiceNane=xe";
Connection con = DriverManager.getConnection(url, "scott", “tiger");
J/send and excute the query
Statenent st=con.createStatenent();
ResultSet rsest.executeQuery("select * from student");
while(rs.next())
Systen.out.println(rs.getInt(a)+* “srs.getString(2)+" “4rs.getString(3))3
}
//close jdbc bjs
rs.close()3
st.close()3
con.close();
Vimain
Viclass
//>Javac TypeSTest. java
//>java TypeTest
Applications on Reflection API
//hppi.iava (gives all classes of inheritance hierarchy for the given java class)
public class Appi
{
public static void main(String args(])throws Exception
C
// \oad the given class to application
Class caClass. forNane(args[@]);
// get super Class of given class
Class sc=c.getSuperclass();
systen,out.println(“The inheritance of given class is");
while(scleaull)
{
system.out printin(™\t\t\t"4sc. getName()) 5
csc}
seme. getSuperclass();
Miwhile
y¢main
Yielass
//>javac Appi.java (compile tine)
7/>java Appl java.lang.String (runtime)
//java Appl java.awt. TextField
2 -App2. java--
//hpp2.Java (gives interfaces implemented by the given java class)
public class App2
{
public static void main(String args[])throws Excertion
{
// load the given inte Application
Class ceClass. forwane (args[0]);
// get the interfaces implenented by given class
Class inter[ ]ec.getinterfaces();
// print interface names
Systen.out.printIn("The interfaces inplenented by"4args[0]);
for(int indsicinter.Length;+4i)
4
System.out-printIn("\t\t*+inter[i].getName());
/for
Himain
iclass
7/>Javac App2. java
/}>5ava_app2 java.lang.String
ichnologies, Opp. Satyam Theat ‘com/nareshit
‘Nares!Naresh i Technologies APPLICATIONS By Mr.Nataraj
//>java App2 java.util Oate ae
- Appa. java-
//app4. java (gives modifiers of the given java class)
import java. 1ang.reflect .Modi fies
public class Appa
public static void main(String args[]) throws Exception
{
/1 oad the given in to Application
Class ¢=Class. forNane(args[@])3
// eet the nodifiers of given class
int x=c.getModifiers();
systen.out.printin(" value is"4x)3
/iprint modifiers
systen.cut.println("The modifiers of "sares[e]);
if(Modifier.isPublic(x))
systen.out.println(*\t\t publi
if (Modifier. isFinal(x))
systen.out.printin(*\t\t final");
Af (Modifier. ishbstract(x))
systen.out printin("\t\t abstract");
}/main
Viclass
I/>javec Appa. java
//>Java Appa java.lang.String
I/>java Appa Java. lang.Integer
7 pS. java~
1/ App5.java (gives the modifiers of the given java class)
import java. lang.reflect.*;
public class Apps
{
public static void main(String args[])throws Exception
{
[/lo2d the given class into Application
Class ceClass.fortiane(args[@]);
// get all the fields of given java class
Field £[Jec.getdeclaredFields();
[/dipslay menber variable details
Systen.out.printin("The Fields of “args[0]);
for(int is0;icF. length;++i)
{
/1 get modifiers of each field
Ant x=f[{}.getNodifiers();
Af (Modifier. isPublic(x))
systen.out.print("\t\t public");
if Modifier. isPrivate(x))
systen.out.print(*\t\t private");
if (Modifier .isProtected(x))
systen.out.print("\t\t protected");
if (todifier. isStatic(x)) :
Systen.out.print("\t\t static”);
if (Wodi fier -isFinal (x))
system.out.print("\t\t final");
{f (Modifier. isVolatile(x))
Systen.out.print("\t\t volatile”);
if (Modifier. isTransient (x))
systen.out.pnint(*\t\t transient");
String ftype=f[1].getType() -gettane();
String fname=f[i].getane();
System.out.printla(" “#ftypet" —“+fname);
Miter
/aain
Wiclass
Apps. java
‘Naresh | Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 71:2Naresh i Technologies APPLICATIONS By MrNataraj
3169 //>java App5 java.lang.String
3178 //>java App5 java. lang. integer
ain -App6. java~
3172 //App6.java (gives all the constructors of given java class)
3173 import java. lang. reflect.*;
3174
3175 public class Apps
3176 {
3177 public static void main(String args{])throws Exception
3178 {
3179 //oad the given class in to app
3180 Class c=Class. forNane(args[2]);
3181 // get the constructors of given java class
3182 Constructor cons[]=c.getDeclaredconstructors();
3183 //orint constructor details
3184 Systen.out.printIn("the constructors of “sargs{@]);
3185 for(int 120;izcons.lengthss+i)
3186 (
3187 //eet modifiers of each constructor
3188 int xecons[i] .getModifiers();
3189 4#(Wodifier. isPublic(x))
3190 System.out.print(*\t public");
319 if (Modifier. isProtected(x))
3192 ‘System.out.print(*\t protected");
3193 Af (Modifier. AsPrivate(x))
3194 systen.out.print("\t private");
3195 // get name of the each constructor
3196 String name=cons[i].getNane();
3197 //get paraneter types of the each constructor
3198 Class parans{J-cons[i] .getParaneterTypes();
3198 System.out.print(" “+name+"(");
3208 for(int ke@3k
javac ApS. java
3209 //>java Apps java.lang.String
3210 //>java Apps java.util.Date
3211
3212,
3213
‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshitNaresh j Technologies JDBC By Mr. Nataraj
NN
Working with BLOB, CLOB, STRUCT, ARRAY
BLOB:
BLOB stands for Binary Large Object. BLOB is used to store large amount of binary data into
database like images.
The oracle.sql.BLOB class includes the following methods:
« getBinaryOutputStream(): Returns a java.io.OutputStream to write data to the BLOB as
a stream.
* getBinaryStream(): Returns the BLOB data for this Blob instance as a stream of bytes.
* getBufferSize(): Returns the ideal buffer size, according to calculations by the JDBC
driver, to use in reading and writing BLOB data. This value is a multiple of the chunk size
{see getChunkSize() below) and is close to 32K,
* getBytes(): Reads from the BLOB data, starting at a specified point, into a supplied
buffer
* getChunkSize(): Returns the Oracle chunking size, which can be specified by the
database administrator when the LOB column is first created. This value, in Oracle
blocks, determines the size of the chunks of data read or written by the LOB data layer
in accessing or modifying the BLOB value. Part of each chunk stores system-related
information, and the rest stores LOB data. Performance is enhanced if read and write
requests use some multiple of the chunk size.
length(): Returns the length of the BLOB in bytes.
position(): Determines the byte position in the BLOB where a given pattern begins.
putBytes(): Writes BLOB data, starting at a specified point, from a supplied buffer.
Below example shows how to store images into database.
ackage com.nit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
= import java.sql.Connection;
import Java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MyBlobInsert
public static void main(String af}){
Connection con = null;
PreparedStatement ps = null;
InputStream fis = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
System.out.printin(con);
Ps = con. prepareStatement("insert into student_profile values(?,2)");
ps.setint(1,19);
« File f=new File("D:\\PAWAN.jp9");
fis = new FileInputStream(f);
ps.setBinaryStream(2, fis, int)f-length());
int count = ps.executeUpdate();
System.out.printIn("Count: "+count);
} catch (ClassNotFoundexception e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.printin(e); .
e.printStackTrace();
'Noresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies JDBC - By Mr. Nataraj
} catch (FileNotFoundException e) {
e,printStackTrace();
} finatly{
null) fis.close();
null) ps.close();
ull) con.close();
} cateh( Exception ex){
ex.printStackTrace();
>
nt
SQL> CREATE TABLE STUDENT_PROFILE(SNO NUMBER(5);SPHOTO BLOB);
Table created.
How to read an image from database table? or Write an example for reading BLOB
from table.
package com.nit;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql. SQLException;
public class RetrievelmageApp {
public static void main(String[] args) throws IOException, SQLException,
ClassNotFoundException { _*
Class.forName(“oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracie:thin.@nit-
11:1521:xe","system","manager");
PréparedStatement ps=con.prepareStatement("select sphoto from student_profile where
sno=19");
FileOutputStream fos=new FileQutputStream("D:\\NIT\\PAWAN.jpg");
ResultSet rs.=ps.executeQuery();
while(rs.next())}{
fos.write(rs.getBytes(1));
}
fos.close();
aaa
CLOB:- .
CLOB Stands for CharacterLargeObject .If a column data type is declared as’a CLOB then in
that column we can store any text filé data.
‘The oracie.sq!.CLOB class includes the fallawing methods:
« getAsciiOutputStream(): Returns a java.io.OutputStream to write data to the CLOB as a
stream. P 1.
+. getAsciiStream(): Returns the CLOB value designated by the Clob object as a stream of
ASCII bytes.
© getBufferSize():. Returns the ideal buffer size, according to calculations by the JDBC
driver, to use in reading and writing CLOB data. This value is a multiple of the chunk
size (see getChunkSize() below) and is close to 32K. .
* getCharacterOutputStream(): Returns a java.io.Writer to write data to the CLOB as a
stream.
+ getCharacterStream(): Returns the CLOB data as a stream of Unicode characters.
* getChars(): Retrieves characters from a specified point in the CLOB data into a character
array.
‘Naresh i Technologies, Opp. Sotyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitWRT ere
arash ) Technologies JDBC By Mr. Nataraj
wnkSize(): Returns the Oracle chunking size, which can be specified by
se administrator when the LOB column is first created. This value, in
determines the size of the chunks of data read or written by the LOB da
essing or modifying the CLOB value. Part of each chunk stores system:
tion and the rest stores LOB data. Performance is enhanced if you mak:
are write requests using some multiple of the chunk size.
+ getSubString(): Retrieves a substring from a specified point in the CLOB data.
+ tength(): Returns the length of the CLOB in characters.
* position(): Determines the character position in the CLOB at which a given substring
egins.
+ putChars(): Writes characters from a character array to a specified point in the CLOB
d
© putst
1g(): Writes a string to a specified point in the CLOB data.
SQL> CREATE TABLE EXAMPLE(EID NUMBER(19),ENAME VARCHAR2(19),ECODE CLOB);
Table created
Write a java program to insert example eid,example ename and example ecode into
above table
cuo8ie?
ae
* ES Chbapp.iava
3 IRE Systembibeary[is56-1
Ee, Referenced libraries
Be optbct4jar-«
ClobApp.java
package com.nit;
import java.io.File;
import java.io.FileReader;
import java.io.ICException;
import java.sal.Connection;
import java.sal.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ClobApp {
public static void main(String[] args)throws
ClassNotFoundexception, SQLException, IOException {
Class.fortvarne(“oracle,jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(*jdbc:oracie:thin: @nit-
11:1521:xe","system","manager");
File f=new File("D:\\NIT\\Test.java");
String sql="INSERT INTO EXAMPLE VALUES(?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setint(1,99);
ps.setString(2," NARESH"
ps.setCharacterStream(3,new FileReader(f),(int)f.length()); .
ps.executeUpdate();
}
a
sm.
uments and SeltingsIAYAPROZECTS|Desthop
Write a java program to get example eid,example ename and example ecode from
table
Example
ClobRetrieveapp.java
package com.nit;
import java.io.FileQutputStream;
Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit- 275:Naresh i Technologies JOBC By Mr. Nataraj
import java.io.IOException;
port java.io.inputStream;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ClobRetrieveapp { .
public static void main(String[] args) throws ClassNotFoundException, SQLException,
IOException {
Class.fortvame(" oracle.jdbc.driver.OracleDriver"
Connection con=DriverManager.getConnection("{dbe:oracie:thin: @nit-
11:1521:xe", "system", "manager");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT *FROM EXAMPLE");
while (rs.next()) {
int eid=rs.getInt(1);
String ename=rs.getString(2);
Clob clob=rs.getClob(3);
InputStream in=clob.getAsciiStream();
FileOutputStream fos=new FileOutputStream("D:\\AdvancedJava\\"+eid-ename+" java");
int ch=in.read();
while(ch!=-1){
fos.write(ch);//storing in file
System.out.printin(ch);//displaying on monitor
ch=in.read();
+
in.close();
fos.close();
}
>
a
Struct(Object)Data Type
This data type ig required in case you want to create a user-defined type in a database.Far
example ,you might need to create a user defined type to represent the address of a student in
a single column.
SB structepp
G8 src
| BB comnt
| BB) CerstudentAddressusingstruct java
|) Bid) insertstudentDetais java
(2) STUDENTADDRESS. java
En comant.dae
{ BD GotstudentAddress.java
HEB JRE Systern Library [lavaSE-1.6]
(BA Referenced Libraries” ,
Ea} ofdbct4 jar - C:\Documents and Settings\JA,
STUDENTADDRESS.java
package com.nit;
import java.sql.SQLData;
import java.sql. SQLException;
import java.sql.SQLInput;
port java.sql.SQLOutput;
public class STUDENTADDRESS implements SQLData{
‘Naresh i Technologies, Opp. Satyam Thectre, Ameerpet, Hyd, Ph: 040-23746666, wwwfb.com/nareshit 76:Naresh i Technologies
By Mr. Nataraj
private String street,city,state,typename
private int fno,pin;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
3
public void-setCity(String city) {
this.city = city;
3
public String getState() {
return state;
+
public void setState(String state) {
this.state = state;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
H
public int getFno() {
return fno;
+
public void setFno(int fno) {
this.fno = fno;
+
public int getPin() {
Feturn pin;
}
public void setPin(int pin) {
this.pin = pin;
@Override
public String getSQLTypeName() throws SQLException {
return typename;
+
@Override
public void readSQL(SQLInput stream, String name) throws SQLException {
fno=stream.readint();
stream.readString();
ream.readString();
state=stream.readString();
pin=stream.readint();
typename=name;
+
@Override
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
public void writeSQL(SQLOutput stream) throws SQLException {
stream,writeint(fno);
stream.writeString (ci‘y);
stream. writeString(state);
stream.writeString(street);
stream.writeInt(pin); :
‘InsertStudentDetails.java
package com.nit;
import java.io.File;
import java.io,FileInputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement:
import java.util.Properties;
public class InsertStudentDetails
public static void main(String[] args) throws Exception{
Driver d=(Driver) (Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Properties p=new Properties();
p.put(*user", "system");
p.put("password", "manager");
Connection con=d.connect("jdbc:oracle:thin:@nit-11:1521:xe", p);
PreparedStatement ps=con.prepareStatement("INSERT INTO A
NARESHIT_STUDENTDETAILS(SNO,PHOTO,PERMENTADDRESS) VALUES(?,?,?)");
ps.setint(i, 99);
File f=new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample
Pictures\\Sunset.jpg");
FileInputStream fis=new FileInputStream(f);
ps.setBinaryStream(2,fis,(int)f.length());
STUDENTADDRESS addr=new STUDENTADDRESS();
addr.setFno(19);
addr.setCity("hyd");
addr.setStreet("Ameerpet");
addr.setPin(500099) ;
addr.setState("AP");
addr.setTypename(“NIT_STUDENTADDR2");
ps.setObject(3,addr);
it i=ps.executeUpdate();
System.dut.printin(*Personal Details of Student 99 inserted successfully");
con.close();
»
GetStudentAddress.java
package com.nit.dao;
port java.sql.Connection;
port java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util. HashMap;
port java.util. Properties;
import com.nit.STUOENTADDRESS;
public class GetStudentAddress {
public static void main(String[] args)throws Exception {
Driver d=(Driver)(Class.forName("“oracle.jdbc.driver. OracleDriver") ,newinstance());
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshitNaresh / Technologies JDBC By Mr. Nataraj
——————————
Properties p=new Properties();
p.put(“user", "system");
p.put("password", "manage:");
Connection con=d.connect("jdbc: oracle: thin: @nit-1:
‘Statement -on.createStatement();
ResultSet rs=st.executeQuery/"SELECT PERMENTADDRESS FROM
NARESHIT_STUDENTDETAILS WHERE SNO=99");
if(rs.next()){
HashMap map=new HashMap();
map.put(“NIT_STUDENTADDR2" ,STUDENTADDRESS.class);
STUDENTADDRESS addr=(STUDENTADDRESS)rs.getObject(1,map);
System.out.printin("Student Address.Found");
System.out.printin("Flatno:"+addr.getFno());
System.out.printin("Street:"+addr.getStreet());
system.out.printin("Pin:"+addr.getPin())
:1521:xe", p);
con.close();
3
3
GetStudentAddressUsingStruct.java
package com.nit; ;
import java.sql.Connection; . . we
import java.sql.Driver;
import java.sq.ResultSet;
import java.sql. Statement;
import java.sq}.Struct;
import java.util.Properties;
public class GetStudentAddressUsingStruct {
public static void main(String[] args)throws Exception {
Drivér d= (Driver) (Class.forvame("oracle.jdbe.driver.OracleDriver").! newinstance()}:
Properties p=new,Properties();
p.put("user", "system");
p.put(“password", ‘imanager");
Connection con=dygonnect("jdbe:oracle:thin: @nit-11:1521:xe", p);
Statement st=con.createStatement();
ResultSet rs=st.executéQuery ("SELECT PERMENTADDRESS FROM
NARESHIT_STUDENTDETAILS WHERE SNO=99");
if(rs.next()){
System.out.printin("Student Address Found");
Struct struct=(Struct)rs.getObject(1);
Object addr{]=struct.getAttributes();
System.out.printin("Flatno:"-+addr{0]);
System.out.printin("Street:"+addr[1]);
System.out.printin("Pin:"+addr[4]);
System.out.printin();
con.close();
} A
}
Output
Student Address Found
Flatno:19
Street:hyd
Pin:500099
‘SQL> CREATE TYPE NIT_STUDENTADDR2 AS OBJECT (FLATNO NUMBER, STREET ~
VARCHAR2(19),CITY VARCHAR2(19),STATE VARCHAR2(19),PINCODE NUMBER)
rechnologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwwnfb.com/nareshiti JoBC By Mr, Nataraj
SS ee
27
Type created.
SQL> CREATE TABLE NARESHIT_STUDENTDETAILS(SNO NUMBER,PHOTO
BLOB,PERMENTADDRESS NIT_STUDENTADDR2,PRESENT_ADDRESS NIT_STUDENTADDR2);
Table created.
The Array Data Type:
The java.sql.Array interface of JDBC API provides an abstraction to understand the JDBC Driver
object that represent a database array type.The Array object is implemented by using an SQL
locator,which indicates that the array object contains a logical pointer to locate the array value
ina database.
12 InsertempPessportDetals
EHS sre .
EB comnt
BB) GetempPassPortDetals,java
LB) InsertempPassPortDetals java
BI-BBA JRE System Library [Javast-L.6]
hai Referenced Libraries:
BG ojdbet4,jar- C:\Docurnents
ettings|8
InsertEmpPassPortDetails.java
package com.nit;
import java.sq|.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.util. Properties;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
public class InsertEmpPassPortDetails {
public static void main(String{] args)throws Exception {
Driver d=(Driver)(Class.forName("oracle.jdbc.driver.OracleDriver"). newInstance();
Properties p=new Properties();
p.put("user”, "system");
p.put("password", "manager");
Connection con=d.connect("jdbc:oracle:thin:@nit-11:1521:xe", p);
PreparedStatement ps=con.prepareStatement("INSERT INTO EMPPASSPORTDETAILS.
VALUES(?,2,?)");
ps.setint(1,99);
ps.setString(2,"9989A555""
String si[}={"v1","v2","v3","v4","v5"};
‘ArrayDescriptor ad=ArrayDescriptor.créateDescriptor("VISA_NOS",con);
ARRAY a=new ARRAY(ad, con, $1);
ps.setArray(3, a);
int i=ps.executeUpdate();
System.out. printin("Rows inserted,Count:"+
con.close();
+ ®
GetEmpPassPortDetails.java
package com.nit;
import java.sql.Array;
import Java.sql.Connection;
import java.sql.Drive
port java.sql.PreparedStatement;
port java.sql. ResultSet;
import java.util. Properties;
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh / Technologies JDBC By Mr. Nataraj
public class GetEmpPassPortDetails {
public static void main(String[] args)throws Exception {
Driver d=(Driver)(Class.forName(“oracle.jdbc.driver.OracleDriver").newInstance());,
Properties p=new Properties()
p.put("user", "system");
p.put(“password", "manager");
Connection con=d,connect("jdbc:oracle:thin: @nit-11:1521:xe", p);
PreparedStatement ps=con.prepareStatement("SELECT PASSPORTNO, VISA_TAKEN FROM
EMPPASSPORTDETAILS WHERE EMPNO=99");
ResultSet rs=ps.executeQuery();
if(rs.next()){
System.out.printin("\n Employee Found, His Passport Details.are:\n");
‘System.out.printin(*PassportNio:"+rs.getString(1)#"\n");
System.out.print("Visa's Taken are :\n\t");
Array a=rs.getArray(2);
ResultSet rs1=a.getResultSet();
boolean flag=rsi-next();
while (flag) {
System.out.printin(rs1.getString(2));
‘1.next();
System.out.print(","); :
System.out.printin("Employee not Found");
con.close();
yt SI
Output
Employee Found,His Passport Details are:
F PassportNo:9989A555
: Visa's Taken are :
SQL> CREATE TYPE VISA_NOS AS VARRAY(5) OF VARCHAR2(19)
2/ = oS
Type created.
SQL> CREATE TABLE EMPPASSPORTDETAILS(EMPNO NUMBER, PASSPORTNO.
= VARCHAR2(19),VISA_TAKEN VISA_NOS);Naresh / Technologies JDBC By Mr. Nataraj
FAQs
JDBC Objective Type Questions & Answers
1. Which statements about JDBC are true? (2 answers)
a. JDBC is an API to connect to relational-, object- and XML data sources
b, JDBC stands for Java DataBase Connectivity
c. JDBC is an API to access relational databases, spreadsheets and flat files
d, JDBC is an API to bridge the object-relational mismatch between OO programs and
relational databases
Ans: b,c
2. Which packages contain the JDBC classes?
a. java.jdbc and javaxjdbe b. java.jdbe and java.jdbe.sql
¢. java.sql and javax.sq) d. java.rdb and javax.rdb
Ans: ¢
3. Which type of driver provides JDBC access via one or more ODBC drivers?
a. Type 1 driver b. Type 2 driver c. Type 3 driver d. Type 4 driver
Ans: a
4, Which type of driver converts JDBC calls into the network protocol used by the
database management system directly?
a. Type 1'driver b.Type2driver c. Type 3driver —_d. Type 4 driver.
Ans: d
5. Which type of Statement can execute parameterized queries?
a. PreparedStatement b. ParameterizedStatement
c. ParameterizedStatement and CallableStatement
e. All kinds of Statements (i.e. which implement a sub interface of Statement)
Ans: a
How can you retrieve information from a ResultSet?
a, By Invoking the method get(..., String type) on the ResultSet, where type is the
database type
b, By invoking the method get(..., Type type) on the ResultSet, where Type is an object
which represents a database type
c. By invoking the method getValue(...), and cast the result to the desired Java type.
d. By invoking the special getter methods on the ResultSet: getString(...), getBoolean (...),
getClob(...)j...
Ansid
7. How can you execute DML statements (i.e. insert, delete, update) in the database?
a. By making use of the insertStatement, DeleteStatement or UpdateStatement classes
b. By invoking the execute(...) or executeUpdate(...) method of a normal Statement object
or a sub-interface object
c. thereof
4. By invoking the executelnsert(...), executeDelete(...) or executeUpdate(...) methods of
the
e. DataModificationStatement object
f. By making use of the execute(...) statement of the DataModificationStatement object
Ans:b
8. How do you know in your Java program that a SQL warning is generated asa result
of executing a SQL statement in the database?
a. You mist catch the checked SQLException which is thrown ‘by ‘the method which
executes the statement :
b. You must catch the unchecked SQLWarningException which Is thrown by the method
which executes the statement
¢. You must invoke the getWarnings() method on the Statement object (or a sub interface
thereof)
d. You must query the ResultSet object about possible warnings generated by the database
Ans:
9. What is, in terms of JDBC, a DataSource?
a. A DataSource is the basic service for managing a set of JDBC drivers
b, A DataSource is the Java representation of a physical data source
‘Naresh i Technologies, Opp. Satyam. Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
c. A DataSource is a registry point for INDI-services
_ d. A DataSource is a factory of connections to a physical data source
Ansid
10. What is the meaning of ResultSet.TYPE_SCROLL_INSENSITIVE
‘a. This means that the ResultSet is insensitive to scrolling
b. This means that the Resultset is sensitive to scrolling, but insensitive to updates, i.e. not
updateable
c, This means that the ResultSet is sensitive to scrolling, but insensitive to changes made
by others
d. The meaning depends on the type of data source, and the type and version of the driver
you use with this data source
Ansic
a. Yes, but only if you call the method openCursor() on the ResultSet, and if the driver and
database support this option
b. Yes, but only if you indicate a concurrency strategy when executing the statement, and
if the driver and database support this option
c. Yes, but only if the ResultSet is an object of class UpdateableResultSet, and if the driver
and database support thisoption
d. No, ResultSets are never updateable. You must explicitly execute DML statements (i.e.
insert, delete and update) to change the data in the underlying database
Ans: b
12, What statements are correct about JDBC transactions (2 correct answers)?
a. A transaction is a set of successfully executed statements in the database
b. A transaction is finished when commit() or roltback() is called on the Connection object,
c. A transaction is finished when commit() or roliback() is called on the Transaction object
d. A transaction is finished when close() is called on the Connection object.
Anstbyd
-13, How can you start a database transaction in the database?
‘a. By asking a Transaction object to your Connection, and calling the method beg
b. By asking a Transaction object to your Connection, and setting the autoCommit
of the Transaction to false
¢. By calling the method beginTransaction() on the Connection object
d. By setting the autoCommit property of the Connection to false, and execute a. "statement
in the database
Ans:d
TRANSACTION_REPEATABLE_READ
a. Dirty reads, non-repeatable reads and phantom reads can occur
b. Dirty reads are prevented; non-repeatable reads and phantom reads can occur
c. Dirty reads and non-repeatable reads are prevented; phantom reads can occur
d. Dirty reads, non-repeatable reads and phantom reads are prevented
Anstc
15, What statements are correct about positioned updates (i.e. cursor updates) in
ResultSets? (2 correct answers) a
a. Using the cursor technique is currently the only possible way to change the data in the.
current row of a ResultSet
b. Insert statements are only supported when using scrollable cursors.
¢. Only scrollable updateable ResultSets can use this approach to change the data In the
current row of a ResultSet
4, The name of the cursor is specified by the setCursorame(String name) method the
Statement object. :
Ans: bd
= 16, How can you execute a stored procedure in the database?
a. Call method execute() on a CallableStatement object
b. Call method executeProcedure() on a Statement object
¢. Call method execute() on a StoredProcedure object
d. Call method run() on’a ProcedureCommand object
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fb.com/naresitNaresh / Technologies i sogc By Mr. Nataraj
Ans: a
47. What happens if you call the method close() on a ResultSet object?
a. The method close() does not exist for a ResultSet. Only Connections can be closed.
b. The database and JDBC resources are released
c. You will get a SQLException, because only Statement objects can close ResultSets
d, The ResultSet, together with the Statement which created it and the Connection from
which the Statement was retrieved, will be closed and release all database and JDBC
resources
Ans: b
18, What happens if you call deleteRow() on a ResultSet object?
a. The row you are positioned on is deleted from the ResultSet, but not from the database,
‘>, The row you are positioned on is deleted from the ResultSet and from the database
¢. The result depends on whether the property synchronizeWithDataSource is set to true or
false
You will get a compile error: the method does not exist because you can nat delete rows
from a ResultSet
Ans:b
19. What statements are correct about batched insert and updates? (2 answers)
a. To create a batch of insert and update statements, you create an object of type, Batch,
and call the method
b. Addstatement(String statement) for each statement you want to execute in the batch
<. Batch insert and updates are only possible when making use of parameterized queries.
d. To do a batched update/insert, you call addBatch(String statement) on a Statement
object for each statement you want to execute in the batch
e. To execute a batched update/insert, you call the executeBatch() method on a Statement
object
20, What is correct about DDL statements (create, grant,...)?
a. DDL statements are treated as normal SQL statements, and are executed by calling the
execute() method on a Statement (or a sub interface thereof) object
b, To execute DDL statements, you have to install additional support files
‘<. DDL statements cannot be executed by making use of JDBC, you should use the native
database tools for this.
d. Support for DDL statements will be a feature of a future release of JDBC
Ans: a
21, The JDBC-ODBC Bridge supports multiple concurrent open statements per
connection?
a. True c. False
Ans:a
22. Which of the following allows non repeatable read in JDBC Connection?
a. TRANSACTION_READ_UNCOMMITTED ——_b. RANSACTION_READ_COMMITTED
c, TRANSACTION_SERIALIZABLE d. TRANSACTION_REPEATABLE_READ
Ans:d
23. Which of the following statements is false as far as different type of statements is
concern in JDBC?
a, Regular Statement b. Prepared Statement
£-Spliodle Statement d. Interim Statement
asi
24, Which of the following methods are needed for loading a database driver in JDBC?
a. registerDriver() method b. Class.forName()
c. Both A and B d. getConnection()
Ans: ¢
25, Which of the following is false as far as type 4 driver
a. Type 4 driver is “native protocol, pure java” driver
b. Type 4 drivers are 100% Java compatible
c Type 4 drivers uses Socket class to connect to the database
d._Type 4 drivers cannot be used with Netscape
concern?
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23748666, www.fo,com/nareshitNaresh / Technologies JDBC By Mr. Nataraj
SS
Ans:d
26. To execute a stored procedure “totalStock”
following code snippet is used?
a. Statement stmt = conne
b. CallableStatement clbstmnt
c, StoreProcedureStatement
stmt=connection.createStoreProcedure(“totalStock()");spstmt.executeQuery();
b. PrepareStatement pstmt =
connection. prepareStatement("totalStock()");pstmt.execute();
in a database server, which of the
n.createStatement();stmt.execute("totalStock()");
con.prepareCall("{call totalSteck}");cs.executeQuery();
27. Which driver is efficient and always preferable for using JDBC applications?
a. Type 4 ‘beType = 1 t. Type = 3 d. Type -2
Ansia
28. JDBC facilitates to store the java objects by using which of the methods of
PreparedStatement
setObject (} 2. setBlob() 3. setClob()
a. 1,2 b. 1,2,3 13 4. 2,3
Ans: b
29. Which statement is static and synchronized in JDBC API?
a.executeQuery() —b, executeUpdate() c. getConnection() d. prepareCall()
Ansic .
30. The JOBC-ODBC bridge is
a. Three tiered b. Multithreaded c. Best for any platform d. All of the above
Ans:b
31, All raw data types (including binary documents or images) should be read and
uploaded to the database as an array of
a. byte b. int
c. boolean d. char
Ans:a
32. The class java.sql.Timestamp has its super class as
a. java.sql.Time b. java.util.Date
¢, java.util. Time d. None of the above
Ans: b
33. BLOB, CLOB, ARRAY and REF type columns can be updated in
a. JDBC 1.0 b. JDBC 4.0
cc. JOBC 2.0 d. JDBC 3.0
Ans: d
34, Which of the following methods finds the maximum number of connections that a
Specific driver can obtain?
a. Database.getMaxConnections b. Connection.getMaxConnections
c, DatabaseMetaData.getMaxConnections —_d, ResultSetMetaData.getMaxConnections
Ans: ¢
35, Are prepared statements actually compiled?
a. Yes, they compiled b. No, they are bound by the JDBC driver ”
Ans: a
36, When the message "No Suitable Driver” occurs?
a. When the driver is not registered by Class.forname(} method
b. When the user name, password and the database does riot match
c. When the JDBC database URL passed is not constructed properly
d, When the type 4 driver is used
Ans: ¢
37. Which driver is called as thin-driver in JDBC?
a. Type-4 driver. Type-1 driver —_c. Type-3 driver d. Type-2 driver
Ans: a
38. How many transaction isolation levels are defined in java.sql.Connection
interface?
a.4 b.3 c5 d.2
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wrw:fo.com/nareshitJDBC By Mr. Nataraj
39, Which method is used to perform DML statements in JDBC?
a.execute() —_b. executeQuery()c, executeUpdate() d. executeResult()
An:
40. What is the disadvantage of Type-4 Native-Protocol Oriver?
a. At client side, a separate driver is needed for each database.
b. Type-4 driver is entirely written in Java
c. The driver converts JDBC calls into vendor-specific database protocol
d. It does not support to read MySQL data.
Ansia
Learn more‘about JDBs ture:
Explain Basic Steps in writing a Java program using JDBC?
JDBC makes the interaction with RDBMS simple and intuitive. When a Java applica
access database :
n needs to
+ Load the RDBMS specific JDBC driver because this driver actually communicates with the
database (Incase of JDBC 4.0 this is automatically loaded).
* Open the connection to database which is then used to send SQL statements and get
results back.
Create JDBC Statement object. This object contains SQL query.
Execute statement which returns resultset(s). ResultSet contains the tuples of database
table as a result of SQL query.
Process the result set.
Close the connection.
Exaplain the JDBC Architecture.
The IDBC Architecture consists of two layers:
+ The JDBC API, which provides the application-to-JDBC Manager connection.
+ The JDBC Driver APS, which supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct
driver is used to access each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases. The location of the driver
manager with respect to the JDBC drivers and the Java application is shown in Figure.
f a
| vaya Applicat
‘Naresh i Téchnologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 86:ee
Naresh i Technine’: JDBC By Mr. Nataraj
What are the main components of JDBC ?
The life cycle of a ser-ist cansists of the following phas
* DriverManages: Manages a list of database drivers “atche connection requests from
the java tion with the proper database driv 3 communication subprotocol.
toccl under JDBC will be used to
The first at recognizes a certain subp:
establish a database Connection.
* Driver: The database communications link, handing all communication with the
database. Noriviaily, once the driver is loaded, the developer need not call it explicitly.
* Connection : Interface with all methods for contacting a database.The connection
object represents cormunication context, i.e., all communication with database is
through connection object only.
+ Statement : Encapsulates an SQL statement which is passed to the database to be
parsed, compiled, planned and executed.
© ResultSet: The ResultSet represents set of rows retrieved due to query execution.
How the JDBC application works?
‘A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer
* Driver layer con
+ The application begins with requesting the Driver:
* An appropriate driver is choosen and is used for establishing the connection. This
connection is given to the application which falls u son layer.
* The application uses this connection to create Statement kind of objects, through which =
SQL commands are sent to backend and obtain the results.
of DriverManager class and the available JDBC drivers.
nager for the connection.
Driver manager
Driver layer Driver classes
, i
Application layer Corinection
‘Statement
I ResultSet
\___upaatecount
Figure: JDBC Application
How do I load a database driver with JDBC 4.0 / Java 6?
Provided the JAR file containing the driver is properly configured, just place the JAR file in the
classpath. Java developers NO longer need to explicitly load JDBC drivers using code
like Class.forName() to register a JDBC driver.The DriverManager class takes care of this. by
automatically locating a suitable driver when the DriverManager.getConnection() method is
called. This feature is backward-compatible, so no changes are needed to the existing JDBC
code.
What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the abstract classes
provided by the JDBC API. Each vendor driver must provide implementations of
the java.sql.Connection, Statement, PreparedStatement, CallableStatement,
ResultSet and Driver.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hy “h: 040-23746666, www-fo.com/nareshitNaresh i Technologies
By Mr. Nataraj
What does the connection object represents?
The connection object represents communication context, |.e., all communication with database
is through connection object only.
What is Statement ?
Statement acts like a vehicle through which SQL
commands can be sent. Through the
connection object we create statement kind of objects.
Through the connection object we create statement kind of objects.
Statement stmt = conn.createStatement();
This method returns object which implements statement interface.
What is PreparedStatement?
A prepared statement is an SQL statement that is precompiled by the database. Through
precompilation, prepared statements improve the performance of SQL commands that are
executed multiple times (given that the database supports prepared statements). Once
compiled, prepared statements can be customized prior to each execution by altering
predefined SQL parameters.
PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET
SALARY = ? WHERE ID = 2");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setint(2, 110592);
Here: conn is an instance of the Connection class and "2" represents parameters. These
parameters must be specified before execution.
What is the difference between a Statement and a PreparedStatement?
Statement
PreparedStatement
|A standard Statement is used to create a Java
representation of a literal SQL statement and
‘execute it on the database.
A PreparedStatement is a precompiled
statement. This means that when the
PreparedStatement is executed, the RDBMS
can just run the PreparedStatement SQL.
statement without having to compile it first.
Statement has to verify its metadata against
the database every time.
While a prepared statement has to verify its
metadata against the database only once.
If you want to execute the SQL statement ohce
go for STATEMENT
If you want to execute a single SQL statement
multiple number of times, then go for
PREPAREDSTATEMENT. PreparedStatement
‘objects can be reused with passing different
values to the queries
What are callable statements ?
Callable statements are used from JDBC application to invoke stored procedures and functions.
How to call a stored procedure from JDBC ?
PL/SQL stored procedures are called from within
JDBC programs by means of the prepareCall()
method of the Connection object created. A call to this method takes variable bind parameters
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Pl
140-23746666, www.fo.com/noreshit BB:FE
Naresh / Technologies By Mr, Nataraj
the
as input parameters as we
CallableStatement ciass.
The following line of code uF
CallableStatemen: «\, nt = conn.prepareCall("{call procns AEN
Here conn is an instance of the Connection class.
What are types of JDBC drivers?
There are four types of drivers defined by JDBC as follows:
+ Type 1: IDBC/oDaC require an ODBC (Open Database Connectivity) driver for
the database to be inst This type of driver works by ¥ ing the submitted
queries into equivalent ODBC queries and forwards them via native API calls directly to
the ODBC driver. 1 pro 10 host redirection capability.
+ Type2: Native API (partly-Java driver)—This type of driver uses @ vendor-specific
driver or database API to interact with the database. An example of such an API is
Oracle OCI (Oracle Call Interface). It also provides no host redirection.
* Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding
database requests to a remote database source using a net server component. How the
net Server component accesses the database is transparent to the client. The client
driver communicates with the net server using a database-independent protocol and the
net server translates this protocol into database calls. This type of driver can access any
database.
rotocol-Net(pure Java driver)—This has 2 same configuration
as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can
access only that vendor's database. Again this is all transparent to the client.
Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.
Which type of JDBC driver is the fastest one?
JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into
vendor specific protocol calls and it directly interacts with the database.
Does the JDBC-ODEC Bridge support multiple concurrent open statements per
connection?
No. You can open only one Statement object per connection when you are using the JDBC-
ODBC Bridge.
Which is the right type of driver to use and when?
© Type I driver is handy for prototyping
+ Type III driver adds security, caching, and connection contro!
+ Type III and Type IV drivers need no pre-installation
What are the standard isolation levels defined by JDBC?
The values are defined in the class java.sql.Connection and are:
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION REPEATABLE_READ
TRANSACTION_SERIALIZABLE
Any given database may not support all of these levels. -
Naresh i Technologies, Opp. Satyam Theatre, Anieerpet, Hyd, Ph: 040-23746666, www.fa.com/nareshit 89:Naresh i Technologies JDBC By Mr. Nataraj
————————————
What is resultset ?
The ResultSet represents set of rows retrieved due to query execution
ResultSet rs = stmt.executeQuery(sqlQuery);
What are the types of resultsets?
The values are defined in the class java.sql.Connection and are:
© TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it
can be advanced only in the forward direction.
© TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but
is insensitive to changes committed by other transactions or other statements in the
‘same transaction,
* TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is
affected by changes committed by other transactions or statements within the same
transaction.
Note: A TYPE_FORWARD_ONLY resultset is always insensitive.
What's the difference between TYPE_SCROLL_INSENSITIVE and
TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE 1
‘A sensitive resultset does NOT represent a
snapshot of data, rather it contains points
to those rows which satisfy the query
condition.
‘An insensitive resultset is like the
‘snapshot of the data in the database when
query was executed.
After we get the resultset the changes
made to data are not visible through the
resultset, and hence they are known as
insensitive.
After we obtain the resultset if the data is.
modified then such modifications are
visible through resultset.
Since a trip is made for every
Performance not effected with insensitive. |‘get’ operation, the performance
|drastically get affected.
What is rowset?
A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity
(JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support
component-based development models like JavaBeans, with a standard set of properties and an
event notification mechanism.
What are the different types of RowSet ?
There are two types of RowSet are there. They are:
* Connected - A connected RowSet object connects to the database once and remains
connected until the application terminates.
* Disconnected - A disconnected RowSet abject connects to the database, executes a
query to retrieve the data from the database and then closes the connection. A program
may change the data in a disconnected RowSet while it is disconnected. Modified data
can be updated in the database after a disconnected RowSet reestablishes the
connection with the database,
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwwfb.com/nareshitNaresh i Technologies JDBC By Mr. Nataraj
— a
What is the need of BatchUpdates?
The BatchUpdates feature
server in one single trip
What is a DataSource?
A DataSource object is the representation of a data source in the Java programming language.
In basic terms,
jovls us Lo 9fOUp SQL statements together and send to database
* A DataSource is a facility for storing data.
‘+ DataSource can be referenced by JNDI.
+ Data Source may point to RDBMS, file System , any DBMS etc..
What are the advantages of DataSource?
The few advantages of data source are :
+ An application does not need to hardcode driver information, as it
* doeswiththeDriverManager,
* The DataSource implementations can easily change the properties of data sources. For
example: There is no need to modify the application cade when making changes to the
database details.
+ The DataSource facility allows developers to implement a DataSource class to take
advantage of featul like connection pooling and distributed transactions,
What is connection pooling? what is the main advantage of using connection pooling?
A connection pool is a mechanism to reuse connections created. Connection poling can
increase performance dramatically by reusing connections rather than creating a new physical
connection each time a connection is requested...
‘Naresh j Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/aareshitNaresh i Technologies SERVLETS By Mr, Nataraj
SERVLETS
Earlier in client- server computing, each application had its own client program and it worked as
a user interface and need to be installed on each user's personal computer. Most web
applications use HTML/XHTML that are mostly supported by all the browsers and web pages are
displayed to the client as static documents. A web page can merely displays static content and
it also lets the user navigate through the content, but a web application provides a more
interactive experience.
Any computer running Servlets or JSP needs to have a container. A container Is nothing but
a plece of software responsible for loading, executing and unloading the Servlets and JSP. While
serviets-can’'be used-to extend the functionality of any Java- enabled server. They are'mostly
used to extend web servers, and are efficient replacement for CGI scripts. CGI was one of the
earliest and most prominent server side dynamic content solutions, so before going forward it is,
very important to know the difference between CGI and the Serviets.
Comman Gateway Interface (CGI)
‘The Common Gateway Interface, which Is normally referred as CGI, was one of the practical
technique developed for creating dynamic content. By using the CGI, a web server passes
requests to an external program and after executing the program the content is sent to the
client as the output. In CGI when a server receives a request it creates a new process to run
the CGI program, so creating a process for each request requires significant server resources
and time, which limits the number of requests that can be processed concurrently. CGI
applications are platform dependent. There is no doubt that CGI played a major role in the
explosion of the Internet but its performance, scalability issues make it less than optimal
solutions,
Java Servlets
Java Serviet is a generic server extension that means a java class can be loaded dynamically to
expand the functionality of a server. Servlets are used with web servers and run inside a Java
Virtual Machine (JVM) on the server so these are safe and portable. Unlike applets they do not
require support for java in the web browser. Unlike CGI, serviets don't use multiple processes
to handle separate request. Servets can be handled by separate threads within the same
process. Servlets are also portable and platform independent.
Web Server Introduction
‘A web server is the combination of computer and the program installed on it. Web server
interacts with the client through a web browser. It delivers the web pages to the client and to
an application by using the web browser and he HTTP protocols respectively. We can also
define the web server as the package of large number of programs installed on a computer
connected to Internet or intranet for downloading the requested files using File Transfer.
Protocol, serving e-mail and building and publishing web pages. A web server works ona dient ”
server model. A computer connected to the Internet or intranet must have a server program.
While talking about Java language then a web server is a server that is used to support the web
component like the Serviet and JSP.
Note that the web server does not support to EJB (business logic component) component.
‘A computer connected to the Internet for providing the services to a small company or a
departmental store may contain the HTTP server (to access and store the web pages and files),
SMTP server (to support mail services), FTP server ( for files downloading) and NNTP server (for
newsgroup). The computer containing all the above servers is called the web server. Internet
service providers and large companies may have ali the servers like HTTP server, SMTP server,
Naresh i Technologies, Opp. Sotyom Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fo.com/nareshit <2Naresh i Technologies SERVLETS By Mr. Nataraj
FTP server and many more on separate machines. In case of Java, a web server can be defined
as the server that only supports to the web component like serviet and jsp. Notice that it does
not support to the business component like EJB.
Servlet Container
Aserviet container is nothing but a compiled, executable program. The main function of the
container is to load, initialize and execute servlets. The serviet container is the official
Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java
Servlet and JavaServer Pages specifications are developed by Sun under the Java Community
Process.
A container handies large number of requests as it.can hold many active servlets, listeners etc.
It is interesting te note here that the container and the objects in a container are
multithreaded. So each object must be thread safe in a container as the multiple requests are
being handled by the container due to the entrance of more than one thread to an object at a
time.
Note : A Servlet container may run stand alone i.e, without a web server or even on another
host.
We can categorize the servlet containers as:
1, A simple servlet container is not fully functional and therefore it can only run very simple
servlets and does the following :
+ Wait for HTTP request.
* Construct a ServietRequest object and a ServietResponse object.
+ If the request is for a static resource, inveke the process methad of the
StaticResourceProcessor instance, passing the ServletRequest and ServletResponse
objects.
+ If the request is for a servlet, load the servlet class and invoke its service method,
passing the ServietRequest and ServietResponse objects. Note that in this servlet
container, the servlet class is loaded every time the serviet is requested.
Il. A fully functional serviet container additionally does the following for each HTTP request for a
serviet:
+ When the servlet is called for the first time, load the servlet class and call its init method
(once only).
+ For each request, construct an instance of javax.serviet.ServietRequest and an instance
of javax.serviet.ServietResponse.
+ Invoke the serviet’s service method, passing the ServietRequest and ServletResponse
objects. -
+ When the servlet class is shut down, call the serviet’s destroy method and unload the
serviet class.
Now lets see what a servlet container does for each HTTP request for a serviet, in
general :
+ The serviet container loads the servlet class and calls the init method of the
servlet as soon as the servlet is called for the first time.
+ Then this container makes an instance of javax.servlet.ServletRequest and
javax.serviet.ServietResponse for each request.
* Then it passes the ServietRequest and ServietResponse objects by invoking the
serviet's service method.
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit =93::Naresh i Technologies SERVLETS By Mr. Nataraj
«Finally, it calls the destroy method and unload the servlet class when the servlet class
is to be shut down.
Introduction to Server Side Program
All of us (or most of us) Would have started programming in Java with the ever famous “Hello
World!” program. If you can recollect, we saved this file with a java extension and later
compiled the program using javac and then executed the class file with java. Apart from
introducing you to the language basics, the point to be noted about this program is that ~ “It is
a client side program”. This means that you write, compile and also execute the program on a
client machine (e.g. Your PC). No doubt, this is the easiest and fastest way to write, compile
and execute programs. But, it has.little practical significance when it comes to real world
*-programming.
1. Why Server Side Programming?
Though it is technically feasible to implement almost any business logic using dient
side programs, logically or functionally it carries no ground when it comes to enterprise
applications (e.g. banking, ait ticketing, e-shopping etc.). To further explain, going by
the client side programming logic; a bank having 10,000 customers would mean that
each customer should have a copy of the program(s) in his or her PC which translates to
10,000 programs! In addition, there are issues like security, resource pooling,
concurrent access and manipulations to the database which simply cannot be handled by
client side programs. The answer to most of the issues cited above is - “Server Side
Programming”. Figure-1 illustrates Server side architecture in the simplest terms.
- Java Service's!
EE Java Server Pages!
Web Server / XML files
Application Server
Databases /
Web Services
Fieure ~ Server Side Proerammine farchitecture)
2. Advantages of Server Side Programs
The list below highlights some of the important advantages of Server Side programs
i. All pragrams reside in one machine called the Server. Any number of remote
machines (called clients) can access the server programs.
ll, New functionalities to existing programs can be added at the server side which
the clients’ can advantage without having to change anything from their side.
iii, Migrating to newer versions, architectures, design patterns, adding patches,
switching to new databases can be done at the server side without having to
bother about clients’ hardware or software capabilities.
‘Naresh i Technologies, Opp. Sotyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www/fo.cam/nareshit 4Naresh i Technologies SERVLETS By Mr. Nataraj
——— —————————————————————
iv, Issues relating to enterprise applications like resource management,
concurrency, session management, security and performance are managed by
service side applications.
v. They are portable and possess the capability to generate dynamic and user-based
content (e.g. displaying transaction information of credit card or debit card
depending on user's choice).
of Server Side Programs
Active Server Pages (ASP)
Java Servlets
Java Server Pages (JSPs)
iv. _ Enterprise Java Beans (EBs)
v. PHP
To summarize, the objective of server side programs is to centrally manage alt programs
relating to a particular application (e.g. Banking, Insurance, e-shopping, etc). Clients with bare
minimum requirement (e.g. Pentium II, Windows XP Professional, MS Internet Explorer and an
internet connection) can experience the power and performance of a Server (e.g. IBM
Mainframe, Unix Server, etc) from a remote location without having to compromise on security
or speed. More importantly, server programs are not only portable but aiso possess the
capability to generate dynamic responses based on user's request.
What is Java Serviets?
Servlets are server side components that provide a powerful mechanism for developing server
side programs. Servlets provide component-based, platform-independent methods for building
Web-based applications, without the performance limitations of CGI. programs. Unlike
proprietary server extension mechanisms (such as the Netscape Server API or Apache
modules), serviets are server as well as platform-independent. This leaves you free to select 2
"best of breed" strategy for your servers, platforms, and tools. Using servlets web developers
can create fast and efficient server side application which can run on any servlet enabled web
server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server
side so it does not checks the browser for compatibility. Serviets can access the entire family of
Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a
library of HTTP-specific calls, receive all the benefits of the mature java language including
portability, performance, reusability, and crash protection. Today servlets are the popular
choice for building interactive web applications. Third-party servlet containers are available for
‘Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of
web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun
Java System Web Server, Sun Java System Application Server and others.
Servlets are not designed for a specific protocols. It is different thing that they are most
commonly used with the HTTP protocols Servlets uses the classes in the java packages
Javax.servlet and javax.serviet.http. Servlets provides a way of creating the sophisticated
server side extensions in a server as they follow the standard framework and use the highly
portable java language.
HTTP Servlet typically used to:
+ Priovide dynamic content like getting the results of a database query and returrting to
the client.
+ Process and/or store the data submitted by the HTML. ;
* Manage information about the state of a stateless HTTP. e.g. an online shopping car
manages request for multiple concurrent customers.
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www-f.com/nareshit
|
|Naresh / Technologies SERVLETS By Mr. Nataraj
Features of Serviets 2.4
In this tutorial you will learn the new features added in Servlet 2.4.
1. Upgraded supports for Http, J2SE, and J2EE: Serviet 2.4 depends on Http1.1 and
J2SE 1.3.
2. Additional ServietRequest methods : In Servlet 2.4 four new methods are added in
the ServietRequest
© getRemotePort(): It returns the IP source port of the client.
© getLocalName(): It returns the host name on which the request was recieved.
© getLocalAddr(): It returns the IP address on which the request was recieved.
© _getLocalPort(): It returns the IP port number.
3, -New.Support for Internationalization.and.charset-choice: To provide support of
internationization, Servlet 2.4 has added two new methods in the ServletResponse
interface.
© setCharacterEncoding(String encoding): The purpose of this method is to set
the response's character encoding. This method helps us to pass a charset
parameter to setContentType(String) or passing a Locale to
setLocale(Locale). We can now avoid setting the charset in the
setContentType("text/html;charset=UTF-8") as setCharacterEncoding()
method pairs with the pre-existing getCharacterEncoding() method to
manipulate and view the response's character encoding.
© getContentType(): It is responsible for returning the response's content type.
The content type can be dynamically set with a combination of
setContentType(), setLocale(), and setCharacterEncoding() calls, and the
method getContentType() provides a way to view the generated type string.
4. New features has been added in RequestDispatcher: In Serviet 2.4 five new
request attributes has been added for providing extra information during a
RequestDispatcher forward() call. This features has been added Is Servlet 2.4 to
know the true original request URI. The following request attributes are:
© javax.serviet.forward.request_uri
o javax.serviet.forward.context_path
© javax.serviet.forward.serviet_path
© Javax.serviet.forward.path_info
o javax.serviet.forward.query_string
5. SingleThreadModel interface has been deprecated: In Servlet 2.4 the
SingleThreadModel interface has been deprecated.
6. HttpSession details and interaction with logins has been clarified: The new
method HttpSession.logout() has been added in Servlet 2.4. Now session allows zero or
negative values in the
element to Indicate sessions should never
time out. If the object in the session can't be serialize in a distributed environment then
it must throw an IllegalArgument€xception.
7. Welcome file behavior and Classloading has been clarified: In servlet 2.4 welcome
file can be a serviet.
8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the
2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in
‘Schema.
Features of Serviet 2.5
This versioh has been released on September 26, 2005 by the Sun MicroSystems. It is not
necessary that all web servers and application servers support the features of Servlet 2.5. Still
most of the popular containers like Tomeat 5.5 and JBoss 4,0 support Servlet 2.4.
The list of the added features is given below:
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 96:Previously in 6r , but now we can have myltiple , like
‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph 040-23746666, www.fb.com/nareshit 97:
Naresh i Technologies SERVLETS By ge"
sy Mr. Nataraj
ee
Dependency on J2SE 5.0: The minimum platform requirement for Servlet 2.5 is JDK
1.5. Servet 2.5 can't be used in versions below than JDK1.5. Alll the available features of
JDK1.5 like generics, autoboxing, an improved for loop etc are guaranteed available to
Servlet 2.5 programmers.
Support For annotations: Annotations provide a mechanism for decorating java code
constructs (classes, methods, fields, etc.) with metadata information. Annotations are
mark code in such a way that code processors may alter their behavior based on the
metadata information.
Several web.xml convenience: Servlet 2.5 introduces several small changes to the
web.xml file to make it more convenient to use. For example while writing a , we can now use an asterisk in a which will represent all
servlets as well as ASP.
Previously we used to do
FilterName
FilterName
Now,
FilterName
*
1g> there used to be only one
abc
/abc/*
/abc/*
Apart from these changes, many more facilities added in web.xml.
4. A Handful of removed restrictions: Serviet 2.5 removed a few restrictions around
error handling and session tracking. Now it has removed the restriction that the could not call the setStatus() method to alter the error code that triggered them.
In session tracking, Serviet 2.5 eased a rule that a servlet called by RequestDispatcher
include() couldn't set response headers.
5, Some edge case clarifications: The servlet 2.4 specification says that before calling
request.getReader() we must call request.setCharacterEncoding(). However there is no
such clarification given why it is so.
= Advantages of Java Servlets
1. Portability
2. Powerful
3. Efficiency
4, Safety
5. Integration
6. Extensibilty
7. Inexpensive
Each of the points are defined below:
s
i
|Naresh / Technologies SERVEETS By Mr. Nataraj
SS ——————
Portal ty
‘As we know that the servlets are written in java and follow well known standardized APIs so
they are highly portable across operating systems and server implementations. We can
develop a servlet on Windows machine running the tomcat server or any other server and later
we can deploy that Servlet effortlessly on any other operating system like Unix server running
on the iPlanet/Netscape Application server. So serviets are write once, run anywhere
(WoRA) program:
Powerful
We can do several things with the serviets which were difficult or even impossible to do with
CGI, for example the servlets can talk directly to the web server while the CGI programs can't
do. Serviets can share data among each other, they even make the database connection pools
easy to implement. They..can maintain the session. by-using the session tracking mechanism
which helps them to maintain information from request to request. It can do many other things
which are difficult to implement in the CGI programs.
Efficiency :
‘As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded
the server, it remains in the server's memory as a single dbject instance. However with servlets
there are N threads but only a single copy of the servlet class. Multiple concurrent requests are
handled by separate threads so we can say that the serviets are highly scalable.
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. Java's
automatic garbage collection and a lack of pointers means that servlets are generally safe from
memory management problems..In servlets we can easily handle the errors due to Java's
exception handling mechanism. If any exception occurs then it.will throw an exception,
Integration .
Servlets are tightly integrated with the server. ‘Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The serviet API is designed in such a way that it’can be easily extensible. As it stands today,
the servlet API support Http Serviets, but in later date it can be extended for another type of
servlets.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web servers you can add
servlet support to it.
What is Serviet?
- Java™ objects which are based on servlet framework and APIs and extend the
functionality of a HTTPServer.
~ Mapped to URLs and managed by container with a simple architecture
~ Available and running on all major web servers and app servers
= Platform and server independent
cGt
- Written in C, C++,Visual Basic and Perl
» Difficult to maintain, non-scalable, nonmanageable
- Prone to security problems of programming language
~ Resource intensive and inefficient
- Platform and application-specific
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23740666, wwwfo.com/nareshitNaresh i Technologies SERVLETS. By Mr. Nataraj
OO —— eS
Serviet
- Written in Java
- Powerful, reliable and efficient
- Improves scalability, reusability (component based)
- Leverages built-in security of Java programming language
- Platform independent and portable
Advantages of Servlet
- No CGI limitations
- Abundant third-party tools and Web servers supporting Servlet
- Access to entire family of Java APIs
- Reliable, better performance and scalability
- Platform and server independent
- Secure ‘
- Most servers allow automatic reloading Serviet’s by administrative action.
What is ISP Technology?
- Enables separation of business logic from presentation
- Presentation is in the form of HTML or XML/XSLT
~ Business logic is implemented as JavaBeans or custom tags
- Better maintainability, reusability
- Extensible via custom tags
- Builds on Servlet technology
What is ISP page?
~ A text-based document capable of returning dynamic content to a client browser
- Contains both static and dynamic content
~ Static content: HTML, XML
~ Dynamic content: programming code, and JavaBeans, custom tags
= Servlets and JSP - Comparison
Serviets __ISP
~~ HTML code in java Javarlike code in HTML
- Any form of Data - Structured Text
- Not easy to author a web page | - Very easy to author a web :
‘ page
_ - Code is compiled into a servlet
ISP Benefits
> Content and display logic are separated
- Simplify development with JSP, JavaBeans and custom tags
- Supports software reuse through the use of components
- Recompile automatically when changes are made to the source file a
~ Easier to author web pages
- Platform-independent
When to use Servlet over JSP
- Extend the functionality of a Web server such as supporting a new file format
- Generate objects that do not contain HTML such as graphs or pie charts
~ Avoid returning HTML directly from your servlets whenever possible
Should I Use Servlet or JSP?
> In practice, serviet and JSP are used together
~via MVC (Model, View, Controller) architecture
~ Serviet handles Controtler
- ISP handles View
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/aareshit,Naresh i Technologies SERVLETS By Mr. Nataraj
What does Servlet Do?
- Receives client request (mostly in the form of HTTP request)
- Extract some information from the request
- Do content generation or business lagic process (possibly by accessing database, invoking
EJBs, etc)
- Create and send response to client (mostly in the form of HTTP response) or forward the
request to another serviet or JSP page
Requests and Responses
- What is a request?
. Information that is sent from client to a server
- Who made the request
- What user-entered data is sent
- Which HTTP headers are sent
- What is a response?
. Information that is sent to client from a server
~ Text(html, plain) or binary(image) data
- HTTP headers, cookies, etc
HTTP
- HTTP request contains
. header
. a method
~ Get: Input form data is passed as part of URL
~ Post: Input form data is passed within message body
= Put
- Header
. request data
HTTP GET and POST
- The most common client requests
« HTTP GET & HTTP POST
- GET requests:
. User entered information is appended to the URL in a query string
+ Can only send limited amount of data
/serviet/ViewCourse?FirstName=Sang&LastName=Shin
- POST requests:
- User entered information is sent as data (not appended to URL)
. Can send any amount of data
Servlet Life Cycle Methods
Invoked by container
~ Container controls life cycle of a servlet
- Defined in
~ Javax.serviet.GenericServlet class or
- init()
« destroy()
- Service() - this is an abstract method
~ javax.serviet.http.HttpServiet class
= doGet(), doPost(), doXxx()
- service() - implementation
4, initQ)
~ Invoked once when the serviet is first instantiated
~ Perform any set-up in this method
. Setting up a database connection
2. destroy()
~ Invoked before servlet instance is removed
= Perform any clean-up
Closing a previously created database connection
3. service() & doGet()/doPost()
‘Naresh
fechnologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, wwwfo.com/nareshit,Naresh / Technologies SERVLETS By Mr. Nataraj
. service() methods take generic requests and responses:
~ Service(ServletRequest request, ServietResponse response)
. doGet() or doPost() take HTTPrequests and responses:
~ doGet(HttpServietRequest request, HttpServietResponse response)
~ doPost(HttpServietRequest request, HttpServietResponse response)
- Things You Do in doGet() & doPost()
~ Extract client-sent information (HTTP parameter) from HTTP request
- Set (Save) and get (read) attributes to/from Scope objects
- Perfarm some business logic or access database
~ Optionally forward the request to other Web components (Serviet/JSP)
- Populate HTTP response message and send it to client
‘Scope Objects
~ Enables sharing information ameng collaborating web components via attributes
maintained in Scope objects
- Attributes maintained in the Scope objects are accessed with
. getAttribute()
. setAttribute()
~ Four Scope objects are defined
— Web context, session, request, page
Four Scope Objects: Accessibility
. Web context (ServietConext)
= Accessible from Web components within a Web context
. Session
~ Accessible from Web components handling a request that belongs to
the session
- Request
~ Accessible from Web components handling the request
. Page
— Accessible from JSP page that creates the object
Four Scope Objects: Class
» Web context
~ javax.serviet.ServietContext
Session
~ javax.serviet.http.HttpSession
. Request
~ subtype of javax.serviet.ServietRequest:
Javax.servlet.http.HttpServietRequest
«Page
~ javax.serviet.jsp.PageContext
What is ServietContext For?
- Used by servets to
~ Set and get context-wide (application-wide) object-valued attributes
— Get request dispatcher . To forward to or include web component
— Access Web context-wde initialization parameters set in the webaxmt
file
— Access Web resources associated with the Web context
- Log
— Access other misc, information
Scope of ServietContext
« Context-wide scope
© Shared by all servlets and JSP pages within a "web application”
--Why it is called “web application scope”
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 10%:Naresh i Technologies SERVLETS By Mr. Nataraj
© A"web application” is a collection of servlets and content installed under a
specific subset of the server's URL namespace and possibly installed via a
* war file
1. All serviets in BookStore web application share same
ServietContext object
© There is one ServletContext object per "web application” per Java Virtual
Machine
How to Access ServietContext Object?
o Within your servlet code, call getServietContext()
© Within your servlet filter code, call getServletContext()
© The ServietContext is contained in ServletConfig object, which the Web server provides
to.a.serviet when. the.serviet is.initialized
~ init (ServietConfig servietConfig) in Servlet interface
Why HttpSession?:
0 Need a mechanism to maintain client state across a series of requests from a same user
(or originating from thei same browser) over some period of time
= Example: Online shopping cart
o Yet, HTTP is stateless
o HttpSession maintains client state
--Used by Servlets to set and get the values of session scope attributes
How to Get HttpSession?
© via getSession() method of a Request object (HttpServietRequest)
What is Serviet Request?
© Contains data passed from client to servlet
© All servlet requests implement ServietRequest interface which defines methods
for accessini
~ Client sent parameters
- Object-valued attributes
~ Locales
Client and server
— Input stream
= Protocol information
— Content type
— If request is made over secure channel (HTTPS)
Request attributes can be set in two ways
= Serviet container itself might set attributes to make available custom information
about a request
o Example: javax.serviet.request.x509Certificate attribute for HTTPS
- Servlet set application-specific attribute
© void setAttribute(java.lang.String name, java.lang.Object 0)
© Embedded into a request before a RequestDispatcher call
Getting Client Information
~ String request.getRemoteAddr().
~ String request.getRemoteHost(......
Get client's IP address
Get client's host name
Getting Server Information
* String request.getServerName()... .g. "www.sun.com”
* int request.getServerPort(). . e.g. Port number "8080"
Getting Misc. Information
Input stream
~ ServletinputStream getInputStream()
~ java.io.BufferedReader getReader()
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit::102:Naresh Technologies SERVLETS By Me. Nataraj
. Protocal
~ java.lang.String getProtocol()
«Content type
~ java.lang.String getContentType()
Is secure or not (if it is HTTPS or not)
= boolean isSecure()
What is HTTP Serviet Request?
* Contains data passed from HTTP client to HTTP serviet
+ Created by servlet container and passed to servlet as a parameter of doGet() or
doPost() methods :
+ HttpServietRequest is an extension of ServietRequest and provides additional methods
for accessing
~ HTTP request URL
. Context, servlet, path, query information
— Misc, HTTP Request header information
~ Authentication type & User security information
- Cookies
~ Session
HTTP Request URL
. Contains the following parts
~ http://[host]:(port]/[request path]?[query string]
HTTP Request URL: [request path]
. http://Thost]:[port]/[request path]?[query string]
. [request path] is made of
~ Context: /
~ Servlet name: /
~ Path information: the rest of it
. Examples
~ http://localhost:8080/hello1/greeting
}080/hello1/greeting.jsp
/daydreamer/catalog/lawn/index.html
HTTP Request URL: [query string]
« http://[host]:(port]/[request path]?[query string]
+ [query string] are composed of a set of parameters and values that are user
entered
+ Two ways query strings are generated
= A query string can explicitly appear in a web page
+ Add To Cart
String bookld = request.getParameter("Add");
- Aquery string is appended to a URL when a form with a GET HTTP method is
submitted S
http://localhost/hellot/greeting?username=Monica+Clinton
: String userName=request.getParameter(*username”)
Context, Path, Query, Parameter Methods
=. String getContextPath()
— . String getQueryString()
— . String getPathinfo()
- _, String getPathTransiated()
HTTP Request Headers
HTTP requests include headers which provide extra information about the request
Example of HTTP 1.1 Request:GET /search? keywords= servlets+ jsp HTTP/ 1.1
o Accept: image/gif, image/ jpg, */*
pp. Satyam Theatre, Ameerpet, Hyd, Ph 040-23746666, www.fo.com/nareshit 103:
‘Naresh i TechnoloNaresh i Technologies SERVLETS By Mr. Nataraj
Accept-Encoding: gzip A
Connection: Keep- Alive -
Cookie: userID= id456578
Host: www.sun.com
Referer: http:/www.sun.com/codecamp.html
© User-Agent: Mozilla/ 4.7 [en] (Win98; U) i
== Accept
© Indicates MIME types browser can handle.
~- Accept-Encoding
© Indicates encoding (e. g., gzip or compress) browser can handle
*- Authorization
© User identification for password- protected pages
© Instead of HTTP authorization, use HTML forms to send username/password and
store info in session object |
=> Connection i
‘© InHTTP 1.1, persistent connection is default
© Serviets should set Content-Length with setContentLength (use _—
ByteArrayOutputStream to determine length of output) to support persistent
connections.
-- Cookie
© Gives cookies sent to client by server sometime earlier. Use getCookies, not
getHeader
-- Host
© Indicates host given in original URL.
© This is required in HTTP 1.1
-- If-Modified-Since
© Indicates client wants page only if it has been changed after specified date.
© Don’t handle this situation directly; implement getLastModified instead.
-- Referer
© URL of referring Web page.
© | Useful for tracking traffic; logged by many servers.
~- User-Agent
© String identifying the browser making the request.
© Use with extreme caution!
ooo00
HTTP Header Methods
o String getHeader(java.lang.String name)
~ value of the specified request header as String
© java.util.Enumeration getHeaders(java.lang.String name)
~ values of the specified request header
© java.util.Enumeration getHeaderNames()
~ names of request headers
© int getintHeader(java.lang.String name)
~ value of the specified request header as an int
Authentication & User Security Information Methods
© String getRemoteUser()
= _name for the client user if the servlet has been password protected, null otherwise
o° String getAuthType()
= _name of the authentication scheme used to protect the servlet
© boolean isUserinRole(java.lang.String role)
= Is user is included in the specified logical "role"?
© String getRemoteUser()
— login of the user making this request, if the user has been authenticated, null
otherwise
Cookie Method (in HTTPServietRequest)
~ Cookie[] getCookies()
0 _an array containing all of the Cookie objects the client sent with this request
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-2374§666, www.fb.com/nareshit 104, Naresh i Technologies SERVLETS By Mr. Nataraj
* What is Servlet Response?
= Contains data passed from servlet to client
All serv ses implement ServietResponse inter’
trieve an output stream
= Indicate content type
: = Indicate whether tc buffer output
= Set localization information
. HttpServietResponse extends ServietResponse
- HTTP response status code
~ Cookies
HTTP Response Status Codes
Why do we need HTTP response status code?
~ Forward client to another page
~ Indicates resource is missing
~ Instruct browser to use cached copy
Methods for Setting HTTPResponse Status Codes
- public void setStatus(int stetusCode)
~ Status codes are defined in HttpServletResponse
~ Status codes are numeric fall into five general categories:
. 100-199 Informational
200-299 Successful
300-399 Redirection
= 400-499 Incomplete
+ 500-599 Server Error
= Default status code is 200 (OK)
Common Status Codes
= 290 (SC_OK)
= Success and document follows
~ Default fot serviets
204 (SC_No_CONTENT)
= Success but no response body
= Browser should keep displaying previous document
301 (SC_MOVED_PERMANENTLY)
= The document moved permanently (indicated in Location header)
~ Browsers go to new location automatically
‘Common Status Codes
302 (SC_MOVED_TEMPORARILY)
© Note the message is "Found"
o Requested document temporarily moved elsewhere (indicated in Location header)
© Browsers go to new location automatically
© Servlets should use sendRedirect, not setStatus, when setting this header
401 (SC_UNAUTHORIZED)
© Browser tried to access password- protected page without proper Authorization
header
404 (SC_NOT_FOUND)
= No such page
Methods for Sending Error
. Error status codes (400-599) can be used in sendError methods.
+ public void sendError(int sc)
- The server may give the error special treatment
- public void sendérror(int code, String message)
~ Wraps message inside small HTML document
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph; 040-23746666, vavw.fe.com/nareshit 105%:Naresh i Technologies SERVLETS By Mr. Nataraj
———————————————————
Header in Http Response
Why HTTP Response Headers?
©. Give forwarding location
©. Specify cookies
>. Supply the page modification date
©. Instruct the browser to reload the page after a designated interval
©. Give the file size so that persistent HTTP connections can be used
©. Designate the type of document being generated
Methods for Setting ArbitraryResponse Headers
© Public void setHeader( String headerName, String headerValue)
- Sets an arbitrary header.
0 public void setDateHeader( String-name, long millisecs)
= Converts milliseconds since 1970 to a date string in GMT format
© public void setintHeader( String name, int headerValue)
- Prevents need to convert int to String before calling setHeader
o addHeader, addDateHeader, addintHeader
— Adds new occurrence of header instead of replacing.
Methods for setting Common Response Headers
setContentType
- Sets the Content- Type header. Servlets almost always use this.
= setContentLength .
~ Sets the Content- Length header. Used for persistent HTTP connections.
— addCookie
~ Adds a value to the Set- Cookie header.
= sendRedirect
= Sets the Location header and changes status code.
Common HTTP 1.1 Response Headers
Location
© Specifies a document's new location.
© Use sendRedirect instead of setting this directly.
. Refresh
© Specifies a delay before the browser automatically reloads a page.
Set-Cookie
o The cookies that browser should remember. Don't set this header directly.
© use addCookie instead,
« Cache-Control (1.1) and Pragma (1.0)
= Ano-cache value prevents browsers from caching page. Serid both headers or check
HTTP version.
« Content- Encoding
— The way document is encoded. Browser reverses this encoding before handling
document,
« Content- Length
— The number of bytes in the response. Used for persistent HTTP connections.
« Content- Type
~ The MIME type of the document being returned.
~ Use setContentType to set this header.
. Last Modified
~ The time document was last changed
= Don't set this header explicitly.
~ provide a getLastModified method instead.
Body in Http Response
Writing a Response Body
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies SERVLETS By Mr. Nataraj
A sarvlet almost always returns a response body
- Response body could either be a PrintWriter or a ServletOutputStream
“Writer
~ Using response.getWriter()
For character-based output
. ServletOutputStream
~ Using response.getOutputStream()
~ For binary (image) data
Handling Errors
» Web container generates default error page
- You can specify custom default page to be displayed instead
« Steps to handle errors
~ Create appropriate error html pages for:error conditions
- Modify the web.xml accordingly
g Error Pages in web.xml
exception.BookNotFoundException
/errorpagei.html
‘exception.BooksNotFoundException
F /etrorpage2.html< /location>
exception.OrderException
/errorpage3.htm|
cae CI
ESE]
sses and Interfaces of the §
TE]
esa, |
«Naresh! Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies SERVLETS
The javax.serviet Package
By Mr. Nataraj
ClassTutertace
‘arerface Servlet
This abstract class canbe wed asthe stating pot for
‘nuplerasnting grclstg. Inpauticula, it implements all the
elcgcethe Gar eapmesuceexeeptte se) vice)
apethod. This abstract class also implements the
Sersertoafta interface hich allows the saudet containerte
assinformation tothe sere,
This interface provides the methodsto extractinfermation
ipma client request
This interface provides the methodsto create and send an
anusorvatgresponseto a cian request
absuract, lass GengricServler
jnterface ServlexConfiig This interface-shich allows the serletcontainertopass
‘tnformationtoa ssn
interface & This interface allows the servlet to communicate with ts
container
class ‘A.ganzzal exception class o sional serlet runtime anrors,
The ‘ava servlet http Package
absELact,..class ‘hs sbvae dassesendthe Cenericserviet cas
used forimplementing HTTP serlets, ie. serdsts Which use
HIDE Souzauests.andsespenses,
lnpaticla it provides stubs forthe
‘slid ama() methods which comespondto
peliPmetoduein the request (GET, POST, HEAD.
2G) A concrete genet can ovemtide the appropriatemethods
tghandle the different HTTP request methods.
This interface extendsthe SeryletRequest interfaceto handle
HOUTPazauess,
This interface extendsthe. ServletResponse interfaceto
‘gigaig and send an appropriate HT IPresponse to an HTTP
TEAM,
lass Hosen yet
interface BttpSeryletRequest
interface WtteSeryletResponse
interface UttpSession ‘This interface provides a way to identify a user across more
than one page request or vist to a Web site andto store
infonmation about that user.
glass Cookie s provides support for cockies to be usedin requests
responses.
‘Naresh i Technologies, Opp. Satyam Theotre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit
108:Naresh i Technologies SERVLETS
Cone TP
n axed interact is essential to developing ard
Methods used in servlet
A Generic servlet contains the following five methods:
<0)
public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet.
By this init() method the servlet gets to know that it has been placed into service.
Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: O40-23746666, www.fo.com/nareshit 109:Naresh i Technologies SERVLETS By Mr, Nataraj
The servlet cannot be put into the service if:
‘+ The init() method does not return within a fixed time set by the web server.
+ It throws a ServletException
Parameters - The init() method takes a ServietConfig object that contains the initialization
parameters and serviet's configuration and throws a ServletException if an exception has
occurred.
service()
public void service(ServietRequest req, ServietResponse res) throws
ServletException, IOException
‘Once the servlet starts.getting. the requests, the service() method is.called.by the servlet
container to respond. The servlet services the client's request with the help of two objects.
These two objects javax.serviet.ServietRequest and javax.serviet.ServietResponse are
passed by the servlet container.
The status code of the response always should be set for a servlet that throws or sends an
error.
Parameters - The service() method takes the ServietRequest object that contains the client's
request and the object ServletResponse contains the servlet's response. The service() method
throws ServletException and IOExceptions exception.
getServietConfig()
public ServletConfig gétServietConfig()
This method contains parameters for in
ation and startup of the servlet and returns a -----~
ServletConfig object. This object is then passed to the init method. When this interface is
implemented then it stores the ServietConfig object in order to return it. It is done by the
generic class which implements this inetrface.
Returns - the ServletConfig object
getServletinfo()
public String getServietInfo()
The information about the servlet is returned by this method like version, author etc. This
method returns a string which should be in the form of plain text and not any kind of markup.
Returns ~ a string that contains the information about the servlet
destroy()
public void destroy()
This method is called when we need to close the servlet. That is before removing a servlet
instance from service, the servlet container calls the destroy() method, Once the servlet
container calls the destroy() method, no service methods will then be called . That is after the
exit of all the threads running in the serviet, the destroy() method is called. Hence, the servlet
gets a chance to clean up all the resources like memory, threads etc which are being held.
Life cycle of a Servlet
The life cycle of a servlet can be categorized into faur parts:
1. Loading and Insatantiation: The serviet container loads the servlet during startup or
when the first request is made, The loading of the serviet depends on the attribute
of web.xml file. If the attribute has a positive
value then the serviet is loaded with loading of the container otherwise it loads when the
first request comes for service. After loading of the servlet, the container creates the
instances of the servlet.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit =110::Naresh i Technologies SERVLETS By Mr. Nataraj
. Initialization: After creating the instances, the servlet container calls the init() method
and passes the serviet initialization parameters to the init() method. The init() must be
called by the Servlet container before the servlet can service any request. The
initialization parameters persist untill the serviet is destroyed. The init() method is called
only once throughout the life cycle of the servlet. The serviet will be available for service
if it is loaded successfully otherwise the serviet container unloads the serviet.
3. Servicing the Request: After successfully completing the initialization process, the
serviet will be available for service. Serviet creates seperate threads for each request.
‘The sevlet container calls the service() method for servicing any request. The service()
method determines the kind of request and calls the appropriate method (doGet() or
doPost()) for handling the request and sends response to the client using the methods of
the response object.
4, Destroying the Servlet: if the serviet is no longer needed for servicing any request,
the servlet container calls the destroy() method . Like the init() method this method is
alo called only once throughout the life cycle of the serviet. Calling the destroy(),
method indicates to the servlet container not to sent the any request for service and the
servlet releases all the resources associated with it. Java Virtual Machine claims for the
memory associated with the resources for garbage collection.
Jereate \-y Initialize Wy Avzilable for
H
Unayatable for, “Heown)
Ciitaicg ton |
‘Destroy |
ae
}
Unload
Serene?
FiguresLife Cycle of a Servlet
Lifecycle:- The procedure followed by the technology to execute an application. The various
stages that arise at the runtime when the application is under execution can be called as life
cycle. .
Note:
Servlets has three lifecycle methods and they are defined in Servlet Interface.
The three lifecycle methods of servlet are:~
Li
2service( )
3.destroy( )
1, init():- init() method would be executed by the container automatically as soon as an object
of the servlet is created. object of the serviet would be created only once. Thus init() method
would be executed only once i.e when the object of the servlet is created for the first time.
2.service():- service() method would be executed by the container automatically as and when
the request is coming to a servlet. container always calis service() method by passing the data
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies SERVLETS By Mr. Nataraj
(i.e coming from the client) in the form of ServietRequest object and address of the client
(from where the request is receive) in the form of ServletResponse object as arguments.
3.destroy():- destroy() method would be executed before object of the Servlet is deleted.
container maintains every servlet object for a certain period of time even if no request is
coming to that servlet. After certain period of time container deletes object of the servlet before
deleting or destroying the servlet object.container automatically calls destroy() method and
executes destroy() method completely and after the execution of the destroy() method, the
servlet object would be completely deleted.
since init(),service() and destroy() methods are automatically executed by the container based
‘on certain conditions representing different stages of a web application or servlet application we
call them s LifeCycle methods of a servlet. The javax.serviet package :
iT “Javax.servier.http
HIT SesstontindiegEvent
i
i
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www/fo.com/nareshit =112::Cee el
Naresh / Technologies SERVLETS By Mr, Nataraj
———_———— void init(ServletConti
javaxservietSewiet | | GateteyQ
void service(ServletRequest Servletitesponse)
ServletConfig getServletConfig()
String getServletinfo()
implements
javax.servlet.GenericServl
snit(ServletConfi
ee ( ig)
init()
extends Dons not imnloment service method
javax.servlet.http.HttpSer doXxx(HttpServietRequest HitpServletRespons
viet }
protected service(HttpServletRequest,
HttpServletResponse)
public service(ServletRequest,ServletResponse)
Understanding two methods of Servlet AP!
1) public void init(servietConfig cg) throws ServletException
Life cycle method
2)public void init() throws ServletException
Not a life cycle method. It is convience method given to programmers.
The javax,servlet.GenericServiet class of servlet API contains both init(ServietConfig cg)
method & init() method. In javax.serviet.http.HttpServlet class there are no init() method
definitions. When instantiation event is raised the servlet container calls init(ServietConfig)
method as life cycle method, but it does not call init() method as life cycle method.
Understanding flow of execution related to both init method:
Scenario 1:
LUGenerieServiet.iava (pre-defined class)
public abstract class GenericServiet implements Serviet{
ServletConfig config;
public void init(ServietConfig cg) throws ServletException
(5)
9; //initialization logic of servlet config object :
public void init() throws ServletExcetption {
/{null body method
+
public servietConfig getServietCorifig() {
return config;
. //other methods of GenericServiet class
class
‘TestSrv.java (Qur Servlet class)
‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 04023746666, www fo.com/nareshitNaresh i Technologies SERVLETS By Mr. Nataraj
(4) (2) (3) (4)
public class TestSrv extends GenericServlet/HttpServlet {
public void init()
«(6)
«(four servlet program related initialization logic
“Viinit()
a)
With respect to above scenario1:
1) End user gives first request to our servlet program (TestSrv) (et us assume no is enabled on this servlet program).
2) Serviet container creates our servlet class‘object using O-param constructor.
3) Servlet container creates ServietConfig object as right hand: object to our serviet class
object and also raises instantiation event.
4) To process instantiation event serviet container calls init(-) life cycle method on our
servlet class object having ServietConfig object as argument value. Since that method is
not available in our serviet class the super class init(-) method(GenericServlet) will be
executed. roy
5) This super class init(-) method contai
calls init() method at the end .
6) init() method of our serviet class(TestSrv) executes and this completes the initialization
process of our servlet program
7) Servlet container creates ServietRequest,ServietResponse objs for current request raises.
request arrival event and it calls public service(-,-) method on our servlet class
object. This method execution will process the request’ and sends the response to
browser window.
oe
's logic to initialize the ServletConfig obj and also
In scenariol our serviet program can get access to ServietConfig object by calling
getServietConfig() method of predefined GenericServiet class in the life cycle methods or
other methods of our servlet program.
ServietConfig cg= getServietConfigk); Inherited method of GenericServiet
class
Note: public methods of super class can be called in sub class methods without objects.
Scenario
ner let.java (pre-defined class!
Public abstract class GenericServiet implements servlet
{
Servletconfig config; :
public void init(ServletConfig cg) {
config=cg;
init();
}
public void init() {
//oull body method
Public ServletConfig getServietConfig() {
return config;
+
‘Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fo.com/nareshitSERVLETS.
= muffother methods of GenericServiet class
}iclass
TestSry.java(Our servlet
(4) (2) (3) (4)
public class Testsrv extends Gen icServiet/HttpServiet
ServletConfig cg;
public void init(ServletConfig ca
t
this.cg = cg; //(5) explicit initialization logic of ServietConfig object
-.- [Jour serviet program related initiliaztin logic
;
public void service(ServietRequest req, ServietResponse res) throws Servietexception,
IOException —{
use cg here
(6)
= In scenario 2 OurServiet program contains init(-) method directly so the controt will
= not go to init(-) method of the GenericServiet class. So programmer must initialize
ServietConfig object in its init(-) methad of servlet program to make it visible to other methods
of these servlet program that means in scenario 2 programmer must not forget the explicit
initialization of ServletConfig object in the init(-) method of his servlet pra
E
£. Scenario 3:
GenericServiet.java (pre-defined class)
public abstract class GenericServiet implements Servlet
{
ServletConfig config;
public void init(ServletConfig cg) throws ServletException {
(6)
config= cg; //initiall:
init();
ion logic of ServietConfig object
Public void init() throws ServietException {
(7) //null method
}
public ServletConfig getServietConfig() {
return config;
+
//other methods of GenericServiet class
jifelass
TestSrv.java (Ourservlet class)
qd) (2) (3) (4)
public class TestSrv extends GenericServiet/HttpServiet
{
public void init(ServletConfig cq) {
(s)
super.
it(eg);
(8)
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 115%:Naresh i Technologies SERVLETS By Mr. Nataraj
/four serviet program realted ization logic
public void service(ServietRequest, ServletResponse res) throws
ServletException, IOException {
(9)
ServietConfig cg=getServietConfig();
3//method
}/class
In scenario 3 programmer can use getServietConfig()to get access to ServietConfig
object to its servlet program.
> In scenario 1 use getServletConfig() method to get access to ServletConfig object.
> In scenario 2 initialize ServietConfig object explicitly in init(-) method to use that object.
> In scenario 3 call super.init(-) method in our init(-) method and also call
getServietConfig() method to get access to ServietConfig object.
‘Always give chance to init(-)method of javax.servlet.GenericServiet class to execute
once during instantiation and initialization process of our servlet program because it initializes
ServletConfig object and makes programmer free from that process. Due to this scenario 1 is
most recommended approach to place init() methods in our servlet program.
; 7 If you place both init(),inti(-) methods in our servlet program which init |
method willbe exceuted? 7 A
i
© since init(-) method is the life cycle method the Servlet container calls int(-) method |
and init(). method will not be executed...
nod is life cycle me
is additional‘inethod?
init() method is a convenience method provide in javax.serviet.GenericServlet dass.
Generally, it is suggested that ini(javax.servlet.ServietConfig) method present in
javax.servlet.GenericSevlet class should be given a change to get excecuted, during servlet’s
initialization. This method, apart from performing initialization of ServietConfig obj, invokes
‘() method at the end.
But if our servlet class contains init(javax.serviet.ServietConfig) method, then due to
method over-riding, container invokes our version of the method. If our method calls the
javax.serviet.GenericServiet's init(javax.serviet.ServletConfig) method, by using super keyword
then no problem. But if the developer forgets this, then initialization is not complete, which may
lead to problems.
To solve the above problem, we place init() method in our servlet class so serviet
container calls init(ServietConfig) method of GenericServlet class as life cycle method and this
method internally calls init().Due to this our servlet class init() executes as shown in
scenario1.so programmer need not to initialize ServletConfig object manually
A good programmer never keeps init{-} method in his servlet program to place the
Initialization llogic of servlet program like creating JDBC connection object. He always keeps
this logic in init() Method even thoug it is not life cycle method.
If init() method is not given in servlet API programmer should follow scenario 2 or
scenario 3 to place init methods and he needs to do some explicit work to see the initialization
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit db:A
patie Naresh i Technologies SERVLETS By Mr, Nataraj
ERS> of ServletConfig abject. Ts overcome this problem servlet api aives init) method as convince
method to the progiai aid programmer can use that method a" cin scenario 1,
If we don't piace any iit() methods then super class(Generis Sei vies init(-) method will
be executed which it interr 4150 calls init() method of same
4: inderstan: two service (-,-) methods and 7 doXxx(}) methods of pre-defined
HttpServiet class:
while we develop our servlet program by extending it from javax.servlet.http.HttpServiet
class we can place request processing logic in our servlet program either by using one of the 2
service(-,-) methods or by using 7 doXxx(-,-) methods
1) public void service(ServietRequest req, ServletRespo
ServietException, IOException
public -) of service(-,-) method1 (Life cycle method)
E 2) protected void service(HttpServietRequest req, HttpServietResponse res)throws
t Servletéxception IOException
protected service(-,-) or service(-,-) method2 (Not a Life cycle method)
3) public void doxxx(HttpServietRequest req, HttpServietResponse res) throws
ServietException, IOException (Not Life cycle mehods)
doXxx- total 7 number of doxxx(-,-) methods are available like doGet(-,-
),doPost(-,-),doDelete(-,-),doPut(-,-), doHead( ‘ace(-,-),doOption(-,-)
Even though 7 doXxx(-,-) methods are there the regularly used doXxx(-,-) methods are
doGet(-,-) & doPost(-,-). Only public service(-,-)/service(-,-) method! is the life cycle method
Servlet container calls this public service(-,-) method as life cycie method when the request
arrival event is raised.
Scenario 1 to understand flow of execution related to service (-,-), doxxx(--)
methods:
//HttpServiet.java( pre-defined class)
public abstract class HttpServiet extends GenericServiet_ implements Serializable
t
public void service(ServietRequest req, ServietResponse res)
throws ServietException, IOException {
(4)
HttpServietRequest request= (HttpServletRequest)req
HttpServietResponse response= (HttpServletResponse)res;
service(request, response);
ay
protected void service(HttpServietRequest req, HttpServletResponse res)
throws Servietexception, IOException
{ (8)
String method=req.getMethod();
If(method.equals("GET”))
doGet(req,res);
elseif(method.equals("POST"))
doPost(req,res);
elseif(method.equals("HEAD"))
doHead(req,res);
elseif(method.equals("DELETE”))
doDelete(req,res);
elseif(method.equais("PUT"))
doPuttreg,res);
elseif{methed, (“OPTIONS”)
doOption(req,res);
hnologies, Opp. Satyam Theatre, Ameerpet, Hyd, Phi: 040-23745566, www.fo.com/narest
sii:Naresh i Technologies SERVLETS By Mr. Nataraj
elseif(method.equals(‘TRACE”))
doTrace(req,res);
else
res.sendError(“Invalid request method");
+
protected void doGet(HttpServietRequest req, HttpServletResponse resp)
throws ServietException, IOException
//send 405 error response to browser window
+ S
protected void doPost(HttpServietRequest req, HttpServietResponse resp)
throws ServietException, IOException
{
J{send.405-ecror response to-browser-window
} 7
protected void doXxx(HttpServietRequest req, HttpServietResponse resp)
throws ServietException, IOException {
//send 405 error response to browser window
} :
}iiclass
Qur servlet program:
L{TestStv.java 8
public class TestSrv extends HttpServiet
t
(1)(GET) (2) (3)
public void doGet(HttpServietRequerst req, HttpServietResponse res)throws
Servietéxception, IOException
{
“//some logic (6)
B
With respect to above scenario code
(1) End user gives request to our servlet program having request method "GET" from
client(browser window).
(2) Serviet container creates or locates our servlet class object ,if created the servlet
container completes the instantiation and initialization related life cycle operations.
(3) Serviet container raises request arrival event and calls public service(-,-) method on
our serviet class object as life cycle method having ServletRequest,ServietResponse
objects as arguments. Since public service(-,-) method is not available in our servlet
program, the super class (pre-defined HttpServiet class) public service(-,-) method
executes.
(4) Tthe public service(-,-) method of pre-defined HttpServiet class converts simple
Serviet Request obj to HttpServietRequest obj,simple ServletResponse obj to
HttpServietResponse obj & calls protected service(-,-) method having these two
objects. Since protected service(-,-) method is not available in our servlet class the
super class ( pre-defined HttpServiet class) protected service(-,-) method will be
executed.
(5) The protected service(-,-) method of pre-defined HttpServlet class reads request
method of client generated request and calls an appropriate doXxx(-,-) method i.e.,
doGet (-,-)method. Since doGet (-,-) method is available in our servlet program that
method will be executed.
(6) The doGet(-,-) method of TestSrv program will process the request & sends
generated response to browser windoa as web page.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit 118:Naresh i Technologies SERVLETS By Mr. Nataraj
Assume the client ma’
situations
1.
52 HTTP request based on GET method in the following
ntains both doGet() and doPost()
a ic service(-,-) of HttpServiet
b. protected service(-,-) of HttpServet
c. doGet(-,-) of our class
2. If our class contains only doPost()
a. public service(-,-) of HttpServiet
b. protected service(-,-) of HttpServiet
c, protected doGet(-,-) of HttpServlet(as our class does not contain doGet(-,-))
d. 405 response back to client.
3. If our class overrides public service(-,-) method, and contains doGet(-,-), doPest(-,-
).
a. public service(-,-) of our class[doGet(-,-) of our class will not get invoked,
because the contro! did not pass on to protected.service(-,-) of HttpServiet].
4. If our class overrides public service(-,-) method, and does not contain doGet(-,-)
a. Public service() of our class
No 405 response back to client.
5. If our class overrides public service(-,-) method and it makes a call to
super.service(-,-) method, and contains doGet(-,-), doPost(-,-)
a. public service(-,-) of our class
b. public service(-,-) of HttpServiet(because of super.service(-,-))
c, protected service(-,-) of HttpServiet
d. doGet(-,-) of our class
6. If our class overrides public service() method, and it makes a call to super.service(-,-
) method, and contains only doPost(-,-)
a. public service(-,-) of our class
b. public service(-,-) of HttpServiet(because of super.service(-,-))
¢. protected service(-,-) of HttpServiet
di protected doGet(-,-) of HttpServiet
e, 405 response back to client
In the execution of our serviet program don't let the control going to doXxx(-,-)
methods of javax.serviet.http.HttpServiet class because they always generate 405 error
response page indicating our servlet is totally incomplete to process the request.
When all the methods of pre-defined tittpServiet class, are concrete methods why
the class itself is given as an abstract class?
note:In java abstract class can have only abstract methods or only concrete methods or
mix of both
Javax.servlet.http.HttpServiet class is abstract, even though none of the methods with in
it are abstract it is because, it contains seven doXxx() methods, to match seven ways of
making HTTP request(GET/POST/DELETE/OPTIONS/TRACE/PUT/HEAD). These methods are the
request processing methods of a HttpServiet, just like service(-,-) methéd for a GenericServiet,
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fo.com/nareshit AIS:Naresh Technologies SERVLETS By Mr. Nataraj
— eee
Since there Is only one request-processing method for GenericServiet, it is defined as
abstract in javax.serviet.GenericServiet class, which makes the developer making his class to
extend javax.serviet.GenericServiet class, to provide implementation only from one method.
But in the case of javax.servlet.http.HttpServiet ciass, if all 9 request-processing
methods are defined as abstract, then every developer who creates a child class for it, has to
provide implementations for all the seven methods, which is quite an issue. So the specification
has made javax.serviet.http.HttpServiet class to contain implementations for all the 9 methods,
but they made the javax.serviet.http.HttpServiet class itself as abstract, which means no
developer can create an instance of it directly.
The seven http request_methods/methodologies
The client can send request to web resource proram of.the web application in seven
different ways by using seven different Http methods. To process these methods based request
in our servlet program we can override and use 7 different doxxx(-,-) methods,
GET (default)
POST
HEAD
PUT
DELETE
TRACE
OPTIONS
vvvvvvv
GET:
Default request method designed to get data from server by generating request without
data or with limited amount of data(max. of 256 kb).
POST: Can send request with unlimited amount of data and gathers data from server as
response.
The response of GET based or POST based request contains everything induding
istesponse body like response headers, miscellaneous nformationyetc, =
Sion a
HEAD:
‘Same as GET but theHEAD based request related response does not contain response body.
1. HEAD based requests are useful to test wether web resource program is present
RR) gt not.
£2. Even though there are 7 request methods the most regularly used request:
teal world while developing jave
PUT:
This is capable of allowing client to place new file or web resource program in already
deployed web application of web server. In real projects after placing websites in the web
server of ISP(Internet Service Providers) machine we use FTP(File Transfer Protocol) application
from our computers to maintain that website. This FTP application uses PUT method request to
add new file or new web resource program in that ISP machine website.
OELETE:
Allows client to send a request having the capability to delete file or web resource
program of web application in the server. FTP application uses this delete method to delete web
Page or document or anything from the hosted web application of the ISP machine based web
server.
‘Naresh i Technologies, Opp. Satyam Theotre, Ameerpet, Hyd, Ph: O40-23746566, www.fb.com/nareshit 720:Naresh i Technologies SERVLETS By Mr. Nataraj
ee
‘TRACE:
This trace method request returns all thes debugging messages and flow of execution
details regarding the request and response of certain web resource programs.
OPTIONS:
The options method based request given to web resource program determines using
which Http request methods that this servlet can be request from client.
For example:
If our servlet program overrides doGet(-,-) method as shown below then the OPTIONS method
based request given to the servlet program returns the following response
Allow: HEAD, GET, OPTIONS, TRACE
Eg:
public class TestSrv extends HttpServiet/GenericServiet
{
public void doGet(HttpServietRequest, HttpServietResponse res)throws
ServletException, IOException
{
>
}
Note: “POST","PUT” are non-idempotent. "GET","HEAD","OPTIONS","TRACE","DELETE” are
idempotent.
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit =:12i.Naresh / Technologies SERVLETS. . By Mr. Natai
Understanding Http
javax.serviet.GenericServiet
Signature: public abstract class GenericServiet extends java.lang.Object implements Serviet,
ServietConfg, java.io Serializable
GenericServiet defines a generic, protocol-independent servlet,
Y GenericServiet gives a blueprint and makes writing servlet easier.
¥ GenericServlet provides simple versions of the lifecycle methods init and destroy and of
the methods in the ServletConfig interface.
¥ GenericServiet implements the log method, declared in the ServietContext interface.
v To write a generic servlet, it is sufficient to override the abstract service method
javax:serviet:http.HttpServiet
Signature: public abstract class HttpServlet extends GenericServlet implements
java.io.Serializable
¥_ HttpServlet defines a HTTP protocol specific servlet.
¥_ HttpServlet gives a blueprint for Http servlet and makes writing them easier.
HttpServiet extends the GenericServiet and hence inherits the properties GenericServiet
Provides an abstract class to be subclassed to create an HTTP serviet suitable for a Web site. A
subclass of HttpServiet must override at least one method, usually one of these:
¥ doGet, if the serviet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
Init and destray, to manage resources that are held for the life of the servlet
getServietinfo, which the serviet uses to provide information about itself
RON 8 5
There's almost no reason to override the service method. service handles standard HTTP
requests by dispatching them to the handler methods for each HTTP request type (the doxxx
methods listed above).
Likewise, there's almost no reason to override the doOptions and doTrace methods.
Servlets typically run on multithreaded servers, so be aware that a serviet must handle
concurrent requests and be careful to synchronize access to shared resources. Shared
resources include in-memory data such as instance or class variables and external objects such
as files, database connections, and network connections,
Constructor:
protected [doDelete(HttpServietRequest req, HttpServletResponse resp)
void | Called by the server (via the service method) to allow a serviet to handle a
|DELETE request. i
protected |doGet(HttpServietRequest req, HittpServietResponse resp) S|
|
void Called by the server (via the service method) to allow a serviet ta handle a
GET request.
protected |a idoHead(HttpServietRequest req, HttpServietResponse resp)
void Receives an HTTP HEAD request from the protected service method and
protected | doOptions(HttpServietRequest req, HttpServletResponse resp)
void} Called by the server (via the service method) to allow a servlet to handle a
! BloRnTONS| NS request.
protected |\doPost(HttpServletRequest req, HttpServletResponse resp) |
Called by the server (via the service method) to allow a servlet to handle a_|
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746566, www.fb.com/nareshit 122:Naresh i Technologies SERVLETS By Mr. Nataraj
‘post “request.
pull HttpServietRequest req, HttpServietResponse resp)
protected
void Called by the server (via the service method) to allow a servet to handle a
Pur request.
‘protected doTrace(HttpServietRequest req, HttpServietResponse resp)
void Called by the server (via the service method) to allow a servlet to handle aj
TRACE request. |
| protected getLastModified(HttpServietRequest req)
1 ong! Returns the time the HttpServietRequest object was last modified, in 1
| 4, 1970 j
|
protected | service( ‘HttpServietRequest req, HitoServietResponse resp) |
void Receives standard HTTP requests from the public service method and |
dispatches them to the doXXX methods defined in this class,
void service(ServietRequest req, ServietResponse res) |
Dispatches client requests to the protected service method. |
eT
Skeleton of a HTTP Seivlet
Janets davex.servdet.
onort Javaxsarvier hate." +
Veeck java.io.
gublic class Serviesskeleton extends Urrnservier {
gublig void InixO throws Sanvlexfacserien { /* taptenentation */} // (1)
eublis void doPost(tinrpsemclerResussk 68s HO
HtinsatulerBesonse resp)
‘Theos SenvlerEsceorion, Ioexcention
Ld twplesentation */ } vo.
aubliis void docex(ixxpservissRewsst £0, : 4@
urpselvlenBesnonss Cap)
ghepas Semilerescention, TAexcenzian
{LP japlezentation */ 3
mublig void destroy { /* ieplesentation */ } 1
aublis String gerssruleningaQ) { /* isplezentation */ } Uy
HTTP headers
HTTP headers allow the client and the server to pass additional information with the request or
the _ response. A request header consists of its case-insensitive name followed by a colon ‘:'
then by its value (without CRLF in it). Leading white space before the value is ignored. Headers
are grouped according the context in which they may appear:
‘These headers apply to both requests and responses but are unrelated to the data eventually
transmitted in the body. They therefore apply only to the message being transmitted. There are
only a few of them and new ones cannot be added without increasing the version number of the
‘Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshitNaresh i Technologies _SERVLETS By Mr. Nataraj
Date:,
HTTP protocol. The exhaustive list for MTTP/1.1 is Cache-Control:, Connectioi
Pragma:, Trailer:, Transfer-Encoding:, Upgrade:, Via: and Warning
Request headers
These headers give more precise information about the resource to be fetched or about the
client itself, Among them oné can find cache-related headers, transforming a GET method in a
conditional GET, like If-Modified-Since:, user-preference information like Accept-Language: or
Accept-Charset: or plain client information like User-Agent:. New request headers cannot
officially be added without increasing the version number of the HTTP protocol. But, it is
common for new request headers to be added if both the server and the client agree on their
meaning. In that case, a client should not assume that they will be handled adequately by the
server;-unknown request headers.are-handled_as-entity headers.
Response headers
These headers give more information about the resource sent back, like. its real iocation
(Location:) or about the server itself, like its name and version (Server:). New response
headers cannot be added without increasing the version number of the HTTP protocol, But, it is
common for new response headers to be added if both the server and the client agree
meaning. In that case, a server should not assume that they will be handled adequately by the
client ; unknown response headers are handled as entity headers.
Entity headers
These headers give more information about the body of the entity, like its length (Content-
Length:), an identifying hash (Content-MDS:), or its MIME-type (Content-Type:). New entity
headers can be added without increasing the version number of the HTTP protocol.
Headers can also be grouped according to how caching and non-caching proxies handle them:
End-to-end headers
These headers must be transmitted to the final recipient of the message; that is, the server for
a request message or the client for a response message. Such a header means that
intermediate proxies must retransmit it unmodified and also that caches must store it.
Hop-by-hop headers
These headers are meaningful only for a single transport-level connection and must not be
retransmitted by proxies or cached. Such headers are: Connection:, Keep-Alive:, Proxy-
Authenticate:, Proxy-Authorization:, TE:, Trailers:, Transfer-Encoding: and Upgrade:. Note that
only hop-by-hop headers may be set using the Connection: general header.
In order to learn about the specific semantic of each header, see its entry in the comprehensive
list of HTTP headers.
Useful request headers
‘Among the numerous HTTP request headers, several are especially useful when set correctly. If
you are bullding your own requests, by using XMLHTTPRequest or when writing an extension:
and sending custom HTTP requests via XPCOM, then it is important to ensure the|
presence of headers that are often set by browsers based on the preferences of the user.
Controlling the language of the resource. Most user-agents, like Firefox, allow the user to set
preference for the language for receiving a resource. The browser translate this into an Accept:
Language: header. It is good practice for web developers, when building specific HTTP requests,
to include such a header too.
Using conditional GET
Caching is a major tool to accelerate the display of web pages. Even when parts of a webpage
are refreshed via an XMLHTTPRequest:, it is a good idea to use the If-Modified-Since: header:
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit 124:Naresh / Technologies SERVLE
By Mr. Nataraj
{and other similar ones) in order to fetch the new content only if it has changed. T
lowers the burden on the network.
proach
Useful response headers
The configuration of a web server is a critical part to ensure good performance and optimal
security of a web site, Among the numerous HTTP response headers, several are of specific
importance and should be configured on the server
Restricting framing
Several cross-sit® scripting (KSS) attacks take advantage of the ability to put th
content inside an or
169 con.nt .MordSrv
170
a1
172
173 nno
ava curl -pattern> /udurl
375 .
176
377
178 pqr
179
180
18
182
183
184 /xisurl
as
186
187
188 xyz
189 com.nt .xnlSrv
190
11
192
393
"Naresh Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www.fb.com/nareshit_-136::Naresh i Technologies APPLICATIONS By MrNataraj
/xmlurl
page. hal
ch1> Welcome
Generate Wish Msg
eserviet> :
wish
com.nt.WishSrv
wish
/wurl
web xml
: MishSrv. java
//Mishsrv.java
package com.nt;
import javax.serviet-*;
import Javax.servlet http. *;
inport java.io.*;
inport java.util.*
public class WishSev extends Httpserviet
{
public void service(HttpServietRequest req,HttpServletResponse res)throus
Servletexception, IOException
{
// get Printhiriter
Printiriter pw=res. gethiniter();
// set content Type
res.setContentType (“text/html”);
//get System Date and Tine
Calendar cl=Calendar. getEnstance();
//eet current hour of the day
int h=cl.get (Calendar. HoUR_OF_DAY);
// generate wish message
a#(ne=12)
w.printIn("ch1> Good Afternoon ");
else
pw.println(“chis Good Night ");
J/add_ hyperlink
pu.printin("
ane="pnane" >
name="page”>
name="vflag" value="no"/>
=18)
pu.printin(""sname +" ur elgible to vote”
else
pw.printin("chi>"+name +" ur not elgible to vote");
(Jada graphical Link
pu.printin("");
protected void doGet(HttpServietRequest red,HttpServietResponse res)
throws ServletException, I0Exception{
system.out.printin("Votersev:doGet(-,-)
process(req, res);
MidoPost(-,-
protected void doPost(HttpServietRequest req;HttpServietResponse res)
throws Servletexception, 1OException{
system.out .print1n( “VoterSrv:doPost(-,-)");
process(req,res);
)
/doPost(
yiclass
[P>Javac -d . votersrv. java
‘
abc
éserviet-class>com.nt.Votersrv
/vturl
‘Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyd, Ph: 040-23746666, www fo.cam/nareshitTT
Naresh i Technologies APPLICATIONS By MrNataraj
‘ input .html
«
chi styles" red > Check Voting flgibility