Unit 2
Unit 2
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,
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.
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.
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
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
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.
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
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.
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
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.
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.
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.
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
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.
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.
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 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.
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.
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
JDBC PROCESS
JNDI
Data source
Connection
Statement
Resultset
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
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.)
Statement Objects
Through the Statement object, SQL statements are sent to the database.
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");
• 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:
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
POSSIBLE QUESTIONS
PART B
(Each Question carries 6 Marks)
PART-C
(One Compulsory Question carries 10 Marks)