0% found this document useful (0 votes)
40 views21 pages

Unit 2

The document discusses database concepts including data, databases, database schemas, and the structure of databases. It then covers the Java Database Connectivity (JDBC) API and its main components and objects for connecting Java applications to databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views21 pages

Unit 2

The document discusses database concepts including data, databases, database schemas, and the structure of databases. It then covers the Java Database Connectivity (JDBC) API and its main components and objects for connecting Java applications to databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

UNIT-II

SYLLABUS

J2EE Database Concepts:Data – Database – Database Schema. JDBC Objects: Driver Types –
Packages – JDBC Process – Database Connection – Statement Objects – Result Set – Meta Data.

ABOUT DATA

The term data means groups of information that represent the qualitative or quantitative attributes of a
variable or set of variables. Data (plural of "datum") are typically the results of me asurements and can be
the basis of graphs, images, or observations of a set of variables. Data are often viewed as the lowest
level of abstraction from which in formation and knowledge are derived. In computer science, data is
anything in a form suitable for use with
w a computer. Data is often distinguished from programs. Data is a
collection of facts, figures and statistics related to an object. Data can be proc essed to create useful
information. Data is a valuable asset for an organization. Data can be used by the managers to perform
effective and successful operations of management. It provides a view of past activities related to the rise
and fall of an organization. It also enables the user to make better decision for futu re. Data is very useful
for generating reports, graphs and statistics.

Example:
Students fill an admission form when they get admission in college. The form consists of raw facts about
the students. These raw facts are student's name, father name, address etc. The purpose of collecting this
data is to maintain the records of the students during their study period in the college.

ABOUT DATABASE
A database is an integrated collection of logically related records or files consolidated into a common
pool that provides data for one or more multiple uses. One way of classifying databases involves the type
of content, for example: bibliographic, full-text, numeric, and image. Software o rganizes the data in a
database according to a database m odel. A number of database architectures exist. Many databases use a
combination of strategies. Databases consist of software-based "containers" that are structured to collect
and store information so users can retrieve, add, update or remove such information in an automatic
fashion. Database programs are designed for users so that they can add or delete any information needed.
The structure of a database is the table, which consists of rows and columns of information.

DATABASE SCHEMA
The schema of a database system is its structure described in a formal language supported by the database
management system (DBMS). In a relational database, the schema defines the tables, the fields,
relationships, views, indexes, packages, procedures, functions, queues, triggers, types, sequences,

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

materialized views, synonyms, database links, directories, Java, XML schemas, and other elements.
Schemas are generally stored in a data dictionary. Although a schema is defined in text database
language, the term is often used to refer to a graphical depiction of the database structure.
Levels of database schema
• Conceptual schema, a map of concepts and their relationships.
• Logical schema, a map of entities and their attributes and relations
• Physical schema, a particular implementation of a logical schema
• Schema object, Oracle database object
Conceptual schema
A conceptual schema or conceptual data model is a map of concepts and their relationships. This
describes the semantics of an or ganization and represents a series of assertions about its nature.
Specifically, it describes the things of significance to an organization (entity classes), about which it is
inclined to collect information, and
characteristics of (attributes) an d associations between pairs of those things of significance
(relationships).
Logical schema
A Logical Schema is a data model of a specific problem domain expressed in ter ms of a particular data
management technology. Without being specific to a particular database management product, it is in
terms of relational tables and columns, object-oriented classes, or XML tags. This is as opposed to a
conceptual data model, which describes the semantics of an organization without reference to technology,
or a physical data model, which describe the particular physical mechanisms used to capture data in a
storage medium. The next step in creating a database, after the logical schema is produced, is to create
the physical schema.
Physical Schema
Physical Schema is a term used in relation to data management. In the ANSI four-schema architecture,
the internal schema was the view of data that involved data management technology. This was as
opposed to the external schema thathreflected the view of each person in the organization, or the
conceptual schema that was the integration of a set of external schemas.
Schema Object
A schema object is a logical data storage structure. Schema objects do not have a one-to-one
correspondence to physical files on disk that store their information. However, Oracle stores a schema
e of the database. The data of each object is physically contained in
object logically within a table space
one or more of the table space's data files. For some objects such as tables, indexes, and clusters, you can
specify how much disk space Oracle allocates for the object within the table space's data files.
There is no relationship between schemas and table spaces: a table space can contain objects from
different schemas, and the objects for a schema can be contained in different table spaces.
Associated with each database user is a schema. A schema is a collection of schema objects. Examples of
schema objects include tables, views, sequences, synonyms, indexes, clusters, database links, snapshots,
procedures, functions, and packages.

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

DATABASE AND PLATFORM PORTABILITY

Data connectivity architecture can either simplify or radically complicate portability among databases,
database versions, and platforms. Ideally, data connectivity components should share a common
architecture that makes it easy to change or upgrade the underlying database infrastructure. Most
software companies and enterprise IT organizations must support more than one database platform – and
more than one version of every platform they support. This can mean also managing g a myriad of data
connectivity methods, driver versions, and client library packages.

Adding a new database or even up grading to a new version of the same database can create substantial
development, integration, and testing work. For example, data connectivity components designed to work
with only one database will handle B LOB/CLOB data types (large binary or character objects) differently
than a component designed to work exclusively with another database. Developers will spend significant
time and effort on additional coding and testing for each new database that they need to support.
Standardizing and simplifying data connectivity architecture dramatically reduces the cost and
complexity associated with supporting multiple database back ends. For independe nt software vendors in
particular, this is a significant business priority.

INTRODUCTION TO JDBC
An application programming Interface (API) is a set of classes, methods and resources that programs can
use to do their work. APIs exist for windowing systems, file systems, database systems, networking
systems, and others. JDBC is a Java API for database connectivity that is part of the Java API developed
by Sun Microsystems. JDBC provides Java developers with an industry standard API for database-
independent connectivity between j ava applications and a wide range of relational database management
systems such as oracle. Informix, Microsoft SQL Server and Sybase.
The API provides a call level interface to the database.
• Connect to a database
• Execute SQL statements to query your database
• Generate query results
• Perform updates, inserts and deletions
• Execute stored procedures
The following figure 2.5.1 shows the components of the JDBC model. In its simplest form, JDBC makes
it possible to do these basic things: The Java application calls JDBC classes and interfaces to submit SQL
statements and retrieve results.

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

Figure 2.5.1 Components of the JDBC Model


The JDBC API is implemented through the JDBC driver. The JDBC Driver is a set of classes that
implement the JDBC interfaces to process JDBC calls and return result sets to a Java application. The
database (or data store) stores the data retrieved by the application using the JDBC Driver.

JDBC OBJECTS
The main objects of the JDBC API include:
• A Data Source object is used to establish connections. Although the Driver Manager can also be
used to establish a connection, connecting through a Data Source object is the preferred method.
• A Connection object controls the connection to the database. An application can alter the
behavior of a connection by invoking the methods associated with this object. An application uses
the connection object to create statements.
▪ Statement, Prepared Statement, and Callable Statement objects are use d for executing SQL
statements. A Prepared Statement object is used when an application plans to reuse a statement
multiple times. The application prepares the SQL it plans to use. Once prepared, the application
can specify values for para meters in the prepared SQL statement. The statement can be executed
multiple times with different parameter values specified for each execution. A Callable Statement
is used to call stored proc edures that return values. The Callable State ment has methods for
retrieving the return values of the stored procedure
A ResultSet object contains the results of a query. A ResultSet is returned to an application when a SQL
query is executed by a statement object. The ResultSet object provides methods for iterating through the
results of the query

BENEFITS OF JDBC
The benefits of using JDBC include the following:
• A developer only needs to know one API to access any relational database
• There is no need to rewrite code for different databases.
• There is no need to know the database vendor’s specific APIs
• It provides a standard API and is vendor independent

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

• Almost every database vendor has some sort of JDBC driver


• JDBC is part of the standard Java 2 platform

JDBC ARCHITECTURE
The JDBC API contains two major sets of interfaces: the first is the JDBC API for application writers,
and the second is the lower-level JDBC driver API for driver writers. JDBC technology drivers fit into
one of four categories. Applications and applets can access databases via the JDB C API using pure Java
JDBC technology-based drivers, as shown in the Figure 2.7.1 below

Figure 2.7.1 JDBC connectivity using ODBC drivers


Left side, Type 1: JDBC-ODBC Bridge plus ODBC Driver
This combination provides JDBC access via ODBC drivers. ODBC binary cod e and in many cases,
database client code must be loaded on each client machine that uses a JDB C-ODBC Bridge. Sun
provides a JDBC-ODBC Bridge driver, which is appropriate for experimental use and for situations in
which no other driver is available.
Right side, Type 2: A native API partly Java technology-enabled driver. This type of driver converts
JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or ot her DBMS. Note that,
like the bridge driver, this style of driver requires that some binary code be loaded on each client
machine.
Right side, Type 3: Pure Java Driver for Database Middleware
This style of driver translates JDBC calls into the middleware vendor's protocol, which is then translated
to a DBMS protocol by a middleware server. The middleware provides connectivity to many different
databases.
Left side, Type 4: Direct-to-Database Pure Java Driver
This style of driver converts JDBC calls into the network protocol used directly by DBMS, allowing a
direct call from the client machine to the DBMS server and providing a practical solution for intranet
access.

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change
database engines without changing database code. The Figure 2.7.2 shows the architecture of JDBC.

.
Figure 2.7.2 JDBC Architecture

JDBC IN J2EE
As a core part of the Java 2 Platform, the JDBC API is available anywhere that the platform is. This
means that your applications can truly write database applications once and access data anywhere. The
JDBC API is included in the Java 2 Platform, Standard Edition (J2SE) and the Java 2 Platform,
Enterprise Edition (J2EE), providin gserver-side functionality for industrial strength scalability.
An example of a J2EE based architecture that includes a JDBC implementation:
Requirements
Software: The Java 2 Platform (eith er the Java 2 SDK, Standard Edition, or the Java 2 SDK, Enterprise
Edition), an SQL database, and a JDBC technology-based driver for that database.
Hardware: Same as for the Java 2 Platform.

TWO-TIER AND THREE-TIER MODELS

The JDBC API supports both two-tier and three-tier models for database access Fig 2.8.1 illustrate two-
tier architecture for data access

Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 22CAP201 UNIT: II BATCH: 2022-2024

Fig 2.8.1 Two tier architecture for data access

In the two-tier model, a Java applet or application talks directly to the data s ource. This requires a
JDBC driver that can communicate with the particular data source being accesse d. 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 the n 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
n 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 ca n provide performance advantages. In Figure 2.8.2: illustrates three-
tier architecture for database access.

Fig 2.8.2 Three-tier architecture for database access


Until recently, the middle tier has typically 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 for middle-tier development.
Prepared by Dr G Anitha, Asso. Prof, Department of CA, KAHE
KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and
security features.
With enterprises increasingly using the Java programming language for writing server code, the
JDBC API is being used more and more in the middle tier of three-tier architecture. Some of the
features that make JDBC a server technology are its support for connection pooling, distributed
transactions, and disconnected rowsets.

DRIVER TYPES

JDBC technology-based drivers generally fit into one of four categories.

JDBC Drivers Types

Sun has defined four JDBC driverr types. These are:


Type 1: JDBC-ODBC Bridge Driver
The first type of JDBC driver is JDBC-ODBC Bridge which provides JDBC access to any
ODBC complaint databases through ODBC drivers. Sun's JDBC-ODBC bridge is example of
type 1 driver.
Type 2: Native -API Partly - Java Driver
Type 2 drivers are developed using native code libraries, which were originally designed for
accessing the database through C/C++. Here a thin code of Java wrap around the native code and
converts JDBC commands to DBMS-specific native calls.
Type 3: JDBC-Net Pure Java Driver
Type 3 drivers are three-tier solutions. This type of driver communicates to a middleware
component which in turn connects to database and provide database connecti vity.
Type 4: Native-Protocol Pure Java Driver
Type 4 drivers are entirely written in Java that communicates directly with vendor's database
through socket connection. Here no translation or middleware layer, are required which improves
performance tremendously

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

JDBC-ODBC Bridge driver (Type 1 JDBC Driver)


The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC
is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no
other alternative is available. In figure 2.10.1 Type 1 JDBC – ODBC Bridge.
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are
already available.

Disadvantages
1. Since the Bridge driver is not written fully in Java, Type1 drivers are not portable
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to
the database, and this applies even in the reverse process. They are the slowest of all driver types.
The client system requires the ODBC Installation to use the driver and Not good for the Web.

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

Figure 2.10.1 Type 1: JDBC-ODBC Bridge

Native-API/partly Java driver (Type 2 JDBC Driver)

y 2 jdbc drivers is that Type 2 drivers convert JDBC calls into


The distinctive characteristic of type
database-specific calls i.e. this driver is specific to a particular database. Some distinctive
characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native
api.

Figure 2.10.2 Type 2: Native API/ Partly Java Driver

Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance
than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also
it uses Native api which is Database specific.

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for
the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.
All Java/Net-protocol driver (Type 3 JDBC Driver)
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then
translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4
drivers.

Figure 2.10.3 Type 3: All Java/ Net-Protocol Driver


Advantage
1. This driver is server-based, so there is no need for any vendor database li brary to be present on
client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web
There are many opportunities to optimize portability, performance, and scalability.

3. The net protocol can be designed to make the client JDBC driver very small and fast to load.
4. The type 3 driver typically provides support for features such as cachin g (connections, query
results, and so on), load balancing, and advanced system administration such as logging and
auditing.
5. This driver is very flexible allows access to multiple databases using one driver
6. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take longer,
since the data comes through the backend server

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

Native-protocol/all-Java driver (Type 4 JDBC Driver)


The Type 4 uses java networking libraries to communicate directly with the database server.

Figure 2.10.4 Type 4: Native-protocol/all-Java driver


Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to
achieve platform independ ence and eliminate deployment administration issues. It is most
suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database
requests to ODBC or a nativev connectivity interface or to pass the request on to another server,
performance is typically quite good
3. You don’t need to install special software on the client or server. Further, these drivers can be
downloaded dynamically.

Disadvantage
With type 4 drivers, the user needs a different driver for each database.

JDBC PACKAGE

The purpose of the JDBC package is to provide vendor-neutral access to relational databases. The
implementation differences of the various databases used are abstracted from the user through the use of
the JDBC API. Though the specification does not indicate that the API is to be used solely for relational
databases, historically it has been used primarily for relational database access.

The developers of the JDBC API specification have tried to keep the API as simple as possible so that it
can be a foundation upon which other APIs are built. For instance, the connector API can be
implemented on top of an existing JDBC API using appropriate resource adapters. JDBC is composed of
a number of interfaces. These interfaces are implemented by driver developers. The API is implemented
by either a vendor or a third party to create a JDBC driver.

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

The Type 4 JDBC driver is considered the best driver to use for two reasons. One reason is that since the
driver has been written completely in Java, it is extremely portable. Another reason is that the driver is
not required to map JDBC calls to corresponding native CLI calls. This avoids the overhead of mapping
logic required by the Type 1 or Type 2 driver, or the overhead of communicating with middleware
required by the Type 3 driver.

Such improvements in efficiency should allow the driver to execute faster than the other types of JDBC
drivers.

JDBC 2.0 API

The JDBC 2.0 API includes the complete


o JDBC API, which includes both core and Optional Package
API, and provides industrial-strength database computing capabilities. It is not, however, limited to SQL
databases; the JDBC 2.0 API makes it possible to access data from virtually any data source with a
tabular format.

The JDBC 2.0 API includes two packages:

• java.sql package--the JDBC 2.0 core API


o JDBC API included in the JDKTM 1.1 release (previously called JDBC 1.2). This API is
compatible with any driver that uses JDBC technology.
o JDBC API included in the Java 2 SDK, Standard Edition, version 1.2 (called the JDBC 2.0
core API). This API includes the JDBC 1.2 API and adds many new features.
• javax.sql package--the JDBC 2.0 Optional Package API. This package extends the functionality
of the JDBC API from a client-side API to a server-side API, and it is an essential part of Java2
SDK, Enterprise Edition technology.

Being an Optional Package, it is not included in the Java 2 Platform SDK, Standard Edition,
version 1.2, but it is readily available from various sources.

o Information about theJDBC 2.0 Optional Package API is available f rom the JDBC web
page. The javax.sql package may also be downloaded from this web site.
o Driver vendors may include the javax.sql package with their products.
o The Java 2 SDK, Enterprise Edition, includes many Optional Package APIs, including the
JDBC 2.0 Optional Package.

The java.sql Package


The java.sql package contains the entire JDBC API that sends SQL (Structured Query Language)
statements to relational databases and retrieves the results of executing those SQL statements.

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

The Driver interface represents a specific JDBC implementation for a particular database system.
Connection represents a connection to a database. The Statement, PreparedStatement, and
CallableStatement interfaces support the execution of various kinds of SQL statements.
ResultSet is a set of results returned by the database in response to a SQL query. The
ResultSetMetaData interface provides metadata about a result set, while DatabaseMetaData
provides metadata about the database as a whole.

The java.sql package contains API for the following:

• Making a connection with a data source


o DriverManager class
o Driver interface
o DriverPropertyInfo class
o Connection interface
• Custom mapping an SQL user-defined type to a class in the Java programming language
o SQLData interface
o SQLInput interface
o SQLOutput interface
• Providing information about the database and the columns of a ResultSet object
o DatabaseMetaData interface
o ResultSetMetaData i n terface
• Throwing exceptions
o SQLException thrown by most methods when there is a problem accessing data and by
some methods for other reasons
o SQLWarning thrown to indicate a warning
o DataTruncation thrown to indicate that data may have been truncated
o BatchUpdateException thrown to indicate that not all commands in a batch update
executed successfully
• Providing security
o SQLPermission interface

Metadata
RowSetMetaData: This interface, derived from the ResultSetMetaData interface, provides information
about the columns in a RowSet object. An application can use RowSetMetaData methods to find out how
many columns the rowset contains and what kind of data each column can contain. The RowSetMetaData
interface provides methods for setting the information about columns, but an application would not
normally use these methods. When an application calls the RowSet method execute, the RowSet object
will contain a new set of rows, and its RowSetMetaData object will have been internally updated to
contain information about the new columns.

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

The Reader/Writer Facility


A RowSet object that implements the RowSetInternal interface ca n call on the RowSetReader object
associated with it to populate itself with data. It can also call on the RowSetWriter object associated with
it to write any changes to its rows back to the data source from which it originally got the rows. A rowset
that remains connected to its data source does not need to use a reader and writer because it can simply
operate on the data source directly.
RowSetInternal:By implementing the RowSetInternal interface, a RowSet obj ect gets access to its
internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current
rows and of the values that immediately preceded the current ones, referred to as the original values. A
rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection
that was passed to it, if any. A rows et uses the RowSetInternal methods behind the scenes to get access to
this information. An application does not normally invoke these methods directly.

RowSetReader: A disconnected RowSet o object that has implemented the RowSetInternal interface can
call on its reader (the RowSetReader object associated with it) to populate it with data. When an
application calls the RowSet.execute method, that method calls on the rowset's reader to do much of the
work. Implementations can vary widely, but generally a reader makes a connection to the data source,
reads data from the data source and populates the rowset with it, and closes the connection. A reader may
also update the RowSetMetaData object for its rowset. The rowset's internal state is also updated, either
by the reader or directly by the method RowSet.execute.

RowSetWriter: A disconnected R owSet object that has implemented the RowSetInternal interface can
call on its writer (the RowSetWriter object associated with it) to write changes back to the underlying
data source.

Implementations may vary widely, but generally, a writer will do the following:
• Make a connection to the data source
• Check to see whether there is a conflict, that is, whether a value that has been changed in the
rowset has also been changed in the data source
• Write the new values to th e data source if there is no conflict
• Close the connection
The RowSet interface may be implemented in any number of ways, and anyone may write an
implementation. Developers are encouraged to use their imaginations in coming up with new ways to use
rowsets

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

JDBC PROCESS

JDBC Data structure

JNDI

Data source

Connection

Statement

Resultset

Figure 2.11.1 Data structure of JDBC

Steps involved in JDBC Process:


1. Load the driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection

12.11.2 JDBC: Details of Process

1. Load the driver


try
{
Class.forName("connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
}

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

catch { ClassNotFoundException cnfe)


{
System.out.println("Error loading driver: " cnfe);
}

2. Define the Connection URL


String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" +_dbName; String sybaseURL =
"jdbc:sybase:Tds:" + host +
":" + port + ":" +
"?SERVICENAME=" + dbName;

3. Establish the Connection


String username = "jay_debesee";
String password = "secret";
Connection connection =_
DriverManager.getConnection(oracleURL,username, password);

• Optionally, look up information about the database

DatabaseMetaData dbMetaData = c onnection.getMetaData();


String productName = dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion = dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion);

4. Create a Statement
Statement statement = connection.createStatement();

5. Execute a Query
String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);

– To modify the database, use executeUpdate, supplying a string that uses UPDATE, INSERT, or
DELETE
– Use setQueryTimeout to specify a maximum delay
to wait for results

6. Process the Result

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

while(resultSet.next()) {
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) + " " +
resultSet.getString(3));
}
First column has index 1, not 0
– ResultSet provides various getXxx methods that
take a colu index or column name a nd returns the data
– You can also access result meta data (column names, etc.)

7. Close the Connection


connection.close();
– Since opening a connection is expensive, postpone this step if additional database operations are
expected

Statement Objects

Through the Statement object, SQL statements are sent to the database.

– Three types of statement objects are available:


• Statement
– For executing a simple SQL state ment
• PreparedStatement
– For executing a precompiled SQL statement passing in parameters
• CallableStatement
– For executing a database stored procedure

Statement Methods
• executeQuery
– Executes the SQL query and r eturns the data in a table (ResultSet)
– The resulting table may be empty but never null
ResultSet results =
statement.executeQuery("SELECT a, b FROM_ table");
• executeUpdate
– Used to execute for INSERT, UPDATE, or DELETE, SQL statements
– The return is the number of rows that were affected in the
database
– Supports Data Definition Language (DDL) statements
CREATE TABLE, DROP TABLE and ALTER TABLE
int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" + _ "WHERE STATUS=0");

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

• execute
– Generic method for executing stored procedures and prepared statements
– Rarely used (for multiple return result sets)
– The statement execution may or may not return a ResultSet (use tatement.getResultSet). If the return value is
true, two or more result sets were produced
• getMaxRows/setMaxRows
– Determines the maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited (return value of 0)
• getQueryTimeout/setQueryTimeout
– Specifies the amount of a ti m e a driver will wait for a statement to complete before throwing a
SQLException

RESULTSET
ResultSet and Cursors
The rows that satisfy a particular query are called the result set. The number of rows returned in a result
set can be zero or more. A user can access the data in a result set using a cursor one row at a time from
top to bottom. A cursor can be thought of as a pointer to the rows of the result set that has the ability to
keep track of which row is currently being accessed. The JDBC API supports a cursor to move both
forward and backward and also allowing it to move to a specified row or to a row whose position is
relative to another row.
Types of Result Sets
The ResultSet interface provides methods for retrieving and manipulating the results of executed queries,
and ResultSet objects can have different functionality and characteristics. These characteristics are result
set type, result set concurrency, and cursor hold ability.
The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the
cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected
by the ResultSet object.
The sensitivity of the ResultSet object is determined by one of three different ResultSet types:
TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only forward, from
before the first row to after the last row.
TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both forward and
backward relative to the current position,
and it can move to an absolute position.
TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position.

Before you can take advantage of these features, however, you need to create a scrollable ResultSet
object. The following line of code illustrates one way to create a scrollable ResultSet object:

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(" .... ");

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet
object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and
TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying
whether a result set is read-only or updatable: CONCUR_ READ_ONLY and
CONCUR UPDATABLE. If you do not specify any constants for the type and updatability of a
ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and
CONCUR_READ_ONLY.
Result Set Methods
When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor,
you can use the following methods:
❖ next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned after the last row.
❖ previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on
a row and false if the cursor is positioned before the first row.
❖ first() - moves the cursor to the first row in the ResultSet object. Returns tru eif the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
❖ last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
❖ beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the
ResultSet object does not contain any rows, this method has
no effect.
❖ afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the
ResultSet object does not contain
n any rows, this method has no effect.
❖ relative(int rows) - moves the cursor relative to its current position.
❖ absolute(int n) - positions thecursor on the n-th row of the ResultSet object

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE


KARPAGAM ACADEMY OF HIGHER EDUCATION

CLASS: I MCA COURSE NAME: J2EE

COURSE CODE: 20CAP201 UNIT: I BATCH: 2020-2022

POSSIBLE QUESTIONS
PART B
(Each Question carries 6 Marks)

1. Explain the different types of Keys in database.


2. Explain JDBC Driver Types
3. Elaborate the steps to create a database schema.
4. Discuss about reading, scrollable, updateable resultset with a program.
5. Describe the steps needed to execute a SQL query using JDBC.
6. Explain J2EE database concepts.
7. Discuss about Normalization process with example table.
8. Briefly discuss about the Statement objects, ResultSet with examples
9. Explain the following:
i) Define data, database, and table
10. Explain about Database connection

PART-C
(One Compulsory Question carries 10 Marks)

1. Discuss the concept of Distributive Systems in J2EE.


2. Discuss the Working Process of JDBC.
3. Explain the concept of Cookies.
4. Differentiate Entity Java Bean and Session Java Bean.
5. Discuss about Java Server Pages

Prepared by Dr Angeline Prasanna G, Ass. Prof, Department of CA, KAHE

You might also like