XML notes
XML notes
Downloaded by Roopa Sk
Introduction
XML stands for Extensible Markup Language. It is a text-based markup language derived
from Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying
how to display it like HTML tags, which are used to display the data.
There are three important characteristics of XML that make it useful in a variety of systems
and solutions −
XML is extensible − XML allows you to create your own self-descriptive tags, or language,
that suits your application.
XML carries the data, does not present it − XML allows you to store the data irrespective
of how it will be presented.
XML is a public standard − XML was developed by an organization called the World Wide
Web Consortium (W3C) and is available as an open standard.
Uses of XML
XML has a variety of uses for Web, e-business, and portable applications.
The following are some of the many applications for which XML is useful:
Web publishing: XML allows you to create interactive pages, allows the customer to
customize those pages, and makes creating e-commerce applications more intuitive. With
XML, you store the data once and then render that content for different viewers or devices
based on style sheet processing using an Extensible Style Language (XSL)/XSL
Transformation (XSLT) processor.
Web searching and automating Web tasks: XML defines the type of information contained
in a document, making it easier to return useful results when searching the Web:
General applications: XML provides a standard method to access information, making it
easier for applications and devices of all kinds to use, store, transmit, and display data.
e-business applications: XML implementations make electronic data interchange (EDI)
more accessible for information interchange, business-to-business transactions, and business-
to- consumer transactions.
Metadata applications: XML makes it easier to express metadata in a portable, reusable
format.
Pervasive computing: XML provides portable and structured information types for display
on pervasive (wireless) computing devices such as personal digital assistants (PDAs),
cellular
Downloaded by Roopa Sk
phones, and others. For example, WML (Wireless Markup Language) and VoiceXML are
currently evolving standards for describing visual and speech-driven wireless device interfaces.
Downloaded by Roopa Sk
Not Allowed Replacement Character
Character Entity Description
< < less than
> > greater than
& & Ampersand
' ' Apostrophe
" " quotation
mark
Downloaded by Roopa Sk
The form of an element declaration for elements that contain elements is as follows:
<! ELEMENT element_name (list of names of child elements) >
Sub elements can be specified as:
<! ELEMENT element_name (#PCDATA) - (i.e parsed character data/string)
Example:
<! ELEMENT department (dept_name, building, budget) >
<! ELEMENT dept_name (#PCDATA) >
<! ELEMENT building (#PCDATA) >
<! ELEMENT budget (#PCDATA) >
In many cases, it is necessary to specify the number of times that a sub element may appear.
This can be done in a DTD declaration by adding a modifier to the sub element specification.
Modifier meaning
+ one or more occurrence
* Zero or more occurrence
? Zero or one occurrence
Example: <!ELEMENT person (parent+, age, spouse?, sibling*)>
In this example, a person element is specified to have the following children elements: one or
more parent elements, one age element, possibly a spouse element, and zero or more sibling
elements.
Attribute Declaration
An attribute declaration must include the name of the element to which the attribute belongs,
the attribute9s name, and its type. Also, it may include a default value.
The general form of an attribute declaration is as follows:
<!ATTLIST element,name attribute_name attribute type [default_value\>
If more than one attribute is declared for a given element, the
declarations can be combined, as in the following example:
<!ATTLIS T element_name
attribute _name_1 attribute type default_value_1
attribute_name_2 attribute_type default_value_2
attribute_name_n attribute_type default_value_n>
possible default values for attributes are:
Downloaded by Roopa Sk
Value Meaning
A value This is the value used if none is specified in an element.
#FIXED value The value which every element will have and which cannot be changed.
#REQUIRED No default value is given; every instance of the element must specify a
value.
#IMPLIED the value may or may not be specified in an element
Declaring Entities
Entities can be defined so that they can be referenced anywhere in the content of an XML
document.
Entities can also be defined so that they can be referenced only in DTDs.
The form of an entity declaration that appears in a DTD follows:
<!ENTITY entity_name " entity_value" >
example of an entity: Suppose that a document includes a large number of references to the
full name of President Kennedy.
You could define an entity to represent his complete name as follows:
<!ENTITY jfk "John Fitzgerald Kennedy">
Any XML document that uses a DTD that includes this declaration can specify the complete
name with just the reference jfk.
Sample DTD---planes.dtd
<?xml version = "1.0" encoding = "utf-8"?>
<!4 planes.dtd - a document type definition for the planes.xml document, which specifies
a list of used airplanes for sale 4>
<!ELEMENT planes_for_sale (ad+)>
<!ELEMENT ad (year, make, model, color, description, price?, seller, location)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT make (#PCDATA)>
<9ELEMENT model (#PCDATA)>
<!ELEMENT color (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT seller (#PCDATA)>
<!ELEMENT location (city, state)>
Downloaded by Roopa Sk
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ATTLIST seller phone CDATA #REQUIRED>
<!ATTLIST seller email CDATA #IMPLIED>
<!ENTITY c "Cessna">
<!ENTITY p "Piper">
<!ENTITY b "Beechcraft">
The following is an xml document which conforms to planes.dtd
<?xml version = "1.0" encoding = "utf-8"?>
<!4 planes.xml - ->
<!DOCTYPE planes_for_sale SYSTEM <planes.dtd=>
<planes_for_sale>
<ad>
<year>1977</year>
<make>dc;</make>
<model>Skyhawk</model>
<color>blue and white</color>
<description>newly painted and in good condition</description>
<price>2000000</price>
<seller phone==123-4566-7890=>Skyway aircraft</seller>
<location>
<city>hyd</city>
<state>TS </state>
</location>
</ad>
</ planes_for_sale >
Downloaded by Roopa Sk
If the DTD is included in the XML code, it must be introduced with
<! DOCTYPE root_name [ and terminated with ]> -- Internal DTD
When the DTD is in its own file, the XML document refers to it with a DOCTYPE
declaration as its second line. This declaration has the following form:
<! DOCTYPE XML_document_root_name SYSTEM "DTD_file_name">--External DTD
XML Namespace
An XML namespace is a collection of element and attribute names used in XML documents.
The name of a namespace usually has the form of a URI.
A namespace declaration for an element is given as the value of the xmlns attribute, as in the
following:
If an element has more than one namespace declaration, they are declared as in the following
example:
The first is declared to be the default namespace; the second defines the prefix, cap:
<states>
xmlns = "http://www.states-info.org/states"
xmlns:cap = "http://www.states-info.org/state-capitals"
<state>
<name> South Dakota </name>
<population> 754844 </population>
<capital>
<cap:name> Pierre </cap:name>
<cap:population> 12429 </cap:population>
</capital>
</state>
</states>
Downloaded by Roopa Sk
XML SCHEMAS
Defining a schema:
Schemas are written from a namespace(schema of schemas): The name of this namespace
is
http://www.w3.org/2001/XMLSchema
element, schema, sequence and string are some names from this namespace Every XML
schema has a single root, schema.
• The schema element must specify the namespace for the schema of schemas from
which the schema8s elements and its attributes will be drawn. It often specifies a prefix
that will be used for the names in the schema. This name space specification appears as
xmlns:xsd = http://www.w3.org/2001/XMLSchema
Every XML schema itself defines a tag set like DTD, which must be named with the
targetNamespace attribute of schema element. The target namespace is specified by
assigining a name space to the target namespace attribute as the following:
targetNamespace = http://cs.uccs.edu/planeSchema
Every top-level element places its name in the target namespace If we want to include
Downloaded by Roopa Sk
nested elements(ie if the names of the elements and attributes that are not defined
directly in the schema element), we must set the elementFormDefault attribute to
qualified.
elementFormDefault = <qualified=
The default namespace which is source of the unprefixed names in
the schema is given with another xmlnsspecification without the
prefix.
xmlns = "http://cs.uccs.edu/planeSchema <
Complete example of opening tag of Schema Element
<xsd:schema
<!-- Namespace for the schema itself -->
xmlns:xsd = http://www.w3.org/2001/XMLSchema
targetNamespace = http://cs.uccs.edu/planeSchema
<!-- Default namespace for this document -->
xmlns = http://cs.uccs.edu/planeSchema.
<!-- Specify non-top-level elements to be in the target namespace-->
elementFormDefault = "qualified= >
One alternative to the preceding opening tag would be to make the XMLSchema names
the default so that they do not need to be prefixed in the schema. Then the names in the
target namespace would need to be prefixed. The following schema tag illustrates this
approach:
Downloaded by Roopa Sk
for the schemaLocation attribute. This attribute is used to name the standard
namespace for instances which includes the name XMLSchema-instance
.(XMLSchema-instance)
xmlns:xsi ==http://www.w3.org/2001/XMLSchema-instance"
3. Specify location where the default namespace is defined, using the schemaLocation
attribute, which is assigned two values namespace and filename.
xsi:schemaLocation ="http://cs.uccs.edu/planeSchema planes.xsd" > Altogether,
the opening root tag of an XML instance of the planes.xsd schema, where the root
element name in the instance is planes, could appear as follows:
Downloaded by Roopa Sk
Schema Data types
Two categories of user-defined schema data types :
1. Simple data type is a data type whose content is restricted to strings only, no attributes
and no nested elements(child elements) .It is possible to add restrictions(facets) to a
datatype inorder to limit its content .
2. Complex datatype can have attributes and nested elements.
• XML Schema defines 44 data types .19 of which are primitive and 25 of which are
derived.
• Primitive datatype: string, Boolean, float, time …
• Predefined Derived datatype: Examples byte, decimal, positiveInteger,.
• User-defined derived data types 3 These datatypes are defined by specifying
restrictions on an existing type,which is then called a basetype. Such user defined types
are derived types. Constraints on derived types are given in terms of facets of the base
type .Ex: interget data type has 8 possible facets : totalDigits,
maxInclusive,,maxExclusive etc.
- Both simple and complex types can be either named or anonymous .
DTDs define global elements (context of reference is irrelevant). But context of reference
is essential in XML schema
Data declarations in an XML schema can be
1. Local ,which appears inside an element that is a child of schema
2. Global, which appears as a child of schema
Defining a simple type:
• Elements are defined in an XML schema with the element tag, which is from the
XMLSchema namespace. Recall that the prefix xsd is normally used for names from this
namespace. Use the element tag and set the nameand typeattributes
<xsd:element name = "bird= type
= "xsd:string= /> The instance
could be :
<bird> Yellow-bellied sap sucker </bird>
• An element can be given default value using default attribute. Default value
is automatically assigned to the element when no other value is specified.
<xsd:element name = "bird= type = "xsd:string= default==Eagle= />
Downloaded by Roopa Sk
• An element can have constant value, using fixed attribute. A fixed value is
automatically assigned to the element , and we cannot specify another value.
<xsd:element name = "bird= type = "xsd:string= fixed==Eagle= />
Declaring User-Defined Types:
• User-Define type is described in a simpleType element, using facets . facets must be
specified in the content of restrictionelement. Restrictons on XML elements are called
facets. Restrictions are used to define acceptable values for XML elements or
attributes. Facets values are specified with the valueattribute.
Downloaded by Roopa Sk
<xsd:element name = "model= type = "xsd:string" />
<xsd:element name = "engine= type = "xsd:string" />
<xsd:element name = "year= type = "xsd:decimal" />
</xsd:sequence>
</xsd:complex
Type>
Example 1:
Downloaded by Roopa Sk
Validating Instances of Schemas:
An XML schema provides a definition of a category of XML documents. However,
developing a schema is of limited value unless there is some mechanical way to
determine whether a given XML instance document confirms to the schema. Several
XML schema validation tools are available eg. xsv(XML schema validator) This can be
used to validate online. Output of xsv is an XML document. When run from command
line output appears without being formated.
If schema is not in the correct format, the validator will report that it could not find the
specified schema.
An XML enabled browser or any other system that can deal with XML documents
cannot possibly know how to format the tags defined in the xml documents. Without a
style sheet that defines presentation styles for the document tags the XML documents
cannot be displayed in a formatted manner. Most contemporary browsers like FX3 have
default style sheets that are used when style sheets are not defined for xml documents.
Downloaded by Roopa Sk
//mail.xml
<?xml version="1.0"?>
<mail>
<to>Rani</to>
<from>Ravi</from>
<heading>Remainder</heading>
<body>
<title>Dear Sister</title>
<wish>Good Morning to you</wish>
<msg>Please dont forget about our parents Wedding Anniversary
today.Be there in
time</msg>
</body>
</mail>
Raw xml document mail.xml
Some of the elements in the display are preceded by dashes. These elements can be
elided (temporarily suppressed) by placing the mouse cursor over the dash and clicking
the left mouse button. For example, if the mouse cursor is placed over the dash to the left
of the first<ad> tag and the left mouse button is clicked, the result is as shown below.
Downloaded by Roopa Sk
6. DISPLAYING XML DOCUMENTS WITH CSS
Style sheet information can be provided to the browser for an xml document in
two ways.
First, a CSS file that has style information for the elements in the XML document
can be developed.
Second the XSLT style sheet technology can be used. Using CSS is effective,
XSLT provides far more power over the appearance of the documents display.
A CSS style sheet for an XML document is just a list of its tags and associated styles. The
connection of an XML document and its style sheet is made through an xmlstylesheet
processing instruction. Displayis used to specify whether an element is to be displayed
inline or in a separate block.
<?xml-stylesheet type = "text/css= href = <planes.css"?>
planes.dtd document
<!ELEMENT planes_for_sale (ad+)>
<!ELEMENT ad (year, make, model, color, description, price?, seller, location)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT make (#PCDATA)>
<!ELEMENT model (#PCDATA)>
Downloaded by Roopa Sk
<!ELEMENT color (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT seller (#PCDATA)>
<!ELEMENT location (city, state)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ATTLIST seller phone CDATA #REQUIRED>
<!ATTLIST seller email CDATA #IMPLIED>
<!ENTITY c "Cessna">
<!ENTITY p "Piper">
<!ENTITY b "Beechcraft">
Planes.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE planes_for_sale SYSTEM "planes.dtd">
<planes_for_sale>
<ad>
<year> 1977 </year>
<make> &c; </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
<description> New paint, nearly new interior,
685 hours SMOH, full IFR King avionics </description>
<price> 23,495 </price>
<seller phone = "555-222-3333"> Skyway Aircraft </seller>
<location>
<city> Rapid City, </city>
<state> South Dakota </state>
</location>
</ad>
</planes_for_sale>
Downloaded by Roopa Sk
With planes.css the display of planes.xml as following:
Downloaded by Roopa Sk
EXTENSIBLE STYLE SHEET LANGUAGE (XSL)
A family of specifications for transforming XML documents. It consist of three
standards:
Xpath: identify parts of xml documents, such as specific elements that are in
specific positions in the document or element that have particular attribute values.
XSLT describes how to transform XML documents into different form or formats
such as HTML
,Plain text etc.
Overview of XSLT
XSLT processors take both an XML document and an XSLT document as input.
The XSLT document is the program to be executed; the XML document is the input data
to the program. Parts of the XML document are selected, possibly modified, and merged
with parts of the XSLT document to form a new document, which is sometimes called an
XSL document. Note that the XSL document is also an XML document, which could be
again the input to an XSLT processor. The output document can be stored for future
use by applications, or it may be immediately displayed by an application, often a
browser. Neither the XSLT document nor the input XML document is changed by the
XSLT processor.
Downloaded by Roopa Sk
XSL Transformations for Presentation
XSLT includes more than 50 formatting object(element) types and more than 230
attributes, so it is a large and complex tag set.
Let9s suppose we have the following sample XML file, students.xml, which is required to be
transformed into a well-formatted HTML document.
students.xml
<?xml version = "1.0"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
We need to define an XSLT style sheet document for the above XML document to meet the
following criteria −
Page should have a title Students.
Page should have a table of student details.
Columns should have following headers: Roll No, First Name, Last Name, Nick
Name, Marks
Table must contain details of the students accordingly.
Step 1: Create XSLT document
Create an XSLT document to meet the above requirements, name it as students.xsl and save
it in the same location where students.xml lies.
Downloaded by Roopa Sk
students.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<!-- xsl stylesheet declaration with xsl namespace:
Namespace tells the xlst processor about which
element is to be processed and which is used for output purpose only
-->
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<!-- xsl template declaration:
template tells the xlst processor about the section of xml
document which is to be formatted. It takes an XPath expression.
In our case, it is matching document root element and will
tell processor to process the entire document with this template.
-->
<xsl:template match = "/">
<!-- HTML tags
Used for formatting purpose. Processor will skip them and browser
will simply render them.
-->
<html>
<body>
<h2>Students</h2>
<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of processing instruction
process the value of the element matching the XPath expression
-->
<xsl:value-of select = "@rollno"/>
</td>
Downloaded by Roopa Sk
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 2: Link the XSLT Document to the XML Document
Update student.xml document with the following xml-stylesheet tag. Set href value to
students.xsl
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
...
</class>
Downloaded by Roopa Sk
Output
<xsl:value-of> tag puts the value of the selected node as per XPath expression, as text.
Declaration
Following is the syntax declaration of <xsl:value-of> element.
<xsl:value-of
select = Expression
disable-output-escaping = "yes" | "no" >
</xsl:value-of>
Downloaded by Roopa Sk
<xsl:for-each
select = Expression >
</xsl:for-each>
XML PROCESSOR :
The DOM representation of an XML document has several advantages over the sequential listing
provided by SAX parsers. First, it has an obvious advantage if any part of the document must be
accessed more than once by the application. Second, if the application must perform any
rearrangement of the elements of the document, it can most easily be done if the whole document is
accessible at the same time. Third, accesses to random parts of the document are possible. Finally,
because the parser sees the whole document before any processing takes place, this approach avoids
any processing of a document that is later found to be invalid.
The process of building the DOM structure of an XML document requires some syntactic analysis
of the document, similar to that done by SAX parsers. In fact, most DOM parsers include a SAX
parser as a front end.
Downloaded by Roopa Sk
J2EE: exploring architecture styles, features of EE platform, web servers
and application servers
J2EE Architecture
- The client/server application architecture.
- Which was a two-tier architecture.
- Evolved over time to a multitier architecture.
- This natural progression occurred as additional tiers were introduced between the end-
user clients and back-end systems.
- Although a multitier architecture brings greater flexibility of design.
- It also increases the
o complexity of building,
o testing, deploying,
o administering, and
o maintaining application components.
Two-Tier Architecture
- The two-tier architecture is also known as the client/server architecture.
- It consists mainly of two tiers:
o data and
o client (GUI).
- The application logic can be located in either the client tier.
- Which results in a fat client or located in the data tier.
- which results in a fat server (see Figure).
Downloaded by Roopa Sk
[ Figure : Two-tier architecture. ]
Three-Tier Architecture
- To address the issues of the two-tier architecture, the application logic will be placed in
its own tier.
- Thus applications can be portioned into three tiers.
- The first tier is referred to as the presentation layer, and consists of the application GUI.
- The middle tier, or the business layer, consists of the business logic to retrieve data for
the user requests.
- The back-end tier, or data layer, consists of the data needed by the application.
- Figure illustrates the three-tier architecture.
Downloaded by Roopa Sk
[ Figure : Three-tier architecture. ]
Note :- 1
- The three-tier architecture is the basis for J2EE applications.
- In which EJBs provide a mechanism to build application logic.
- While JSPs and servlets abstract the presentation layer and allow interaction with
the business layer.
- One important feature of the three-tier architecture is sharing system resources by
all clients.
- Which results in :
o highly efficient,
o scalable,
o secure, and
o reliable applications.
Downloaded by Roopa Sk
Multitier J2EE Architecture
- Multitier (or n-tier) architecture differs from the three-tier architecture in viewing each
tier logically.
- Rather than physically.
- The application logic, for example, can be split into more than one layer; the
business logic tier and the presentation logic tier.
- Similarly, the user interface is partitioned into the client tier and the presentation tier.
- A multitier architecture determines where the software components that make up a
computing system are executed in relation to each other and to the hardware, network,
and users.
- J2EE is a multitier architecture, which partitions the application into client,
o presentation logic,
o business logic, and
o enterprise information tiers.
Note : - 2
- The J2EE platform is designed not only to support a multitier architecture to
partition applications.
- But also to provide infrastructure common services to reduce the complexity
of developing and deploying these applications.
- Other than multitier, the J2EE architecture provides the enterprise with
common infrastructure services.
- Which help in developing and deploying :
o portable,
o secure and
o transactional applications.
- The J2EE architecture partitions enterprise applications into three fundamental parts:
o components,
o containers, and
o connectors.
Downloaded by Roopa Sk
- Components are the key focus of application developers.
- Whereas system vendors implement containers and
- Connectors to hide complexity and enhance portability.
- Enterprise Java applications can run on any J2EE-compliant application server.
Note :- 3
- Multitier distributed applications follow the Model-View-Controller (MVC) paradigm,.
- This design pattern provides clean separation between tiers.
- Using this paradigm, the model (data tier) is separated from the view (client
and presentation tiers).
- Similarly, the controller (the application logic tier) is separated from both the view and
the model.
- Containers transparently provide common services :
o including transaction,
o security,
o persistence, and
o resource pooling, to both clients and components.
Features Java EE
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is
currently known as Jakarta EE. It is a set of specifications wrapping around Java SE
(Standard Edition). The Java EE provides a platform for developers with enterprise features
such as distributed computing and web services. Java EE applications are usually run on
reference run
Downloaded by Roopa Sk
times such as microservers or application servers. Examples of some contexts where Java
EE is used are e-commerce, accounting, banking information systems.
Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing
from database in a transactional way, managing distributed queues. The Java EE contains
several APIs which have the functionalities of base Java SE APIs such as Enterprise
JavaBeans, connectors, Servlets, Java Server Pages and several web service technologies.
Downloaded by Roopa Sk
o Java API for JSON Binding- It is a set of specifications provide for binding or parsing
a JSON file into Java classes.
o Java Architecture for XML Binding- It allows binding of xml into Java objects.
o Java API for XML Web Services- SOAP is an xml based protocol to access web
services over http. This API allows you to create SOAP web services.
Server is a device or a computer program that accepts and responds to the request made by other
program, known as client. It is used to manage the network resources and for running the
program or software that provides services.
1. Web Server
2. Application Server
Web Server
Downloaded by Roopa Sk
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can't be used for EJB.
It is a computer where the web content can be stored. In general web server can be used to
host the web sites but there also used some other web servers also such as FTP, email,
storage, gaming etc.
It can respond to the client request in either of the following two possible ways:
below:
Important points
o If the requested web page at the client side is not found, then web server will sends
the HTTP response: Error 404 Not found.
o When the web server searching the requested page if requested page is found then it
will send to the client with an HTTP response.
o If the client requests some other resources then web server will contact to application
server and data is store for constructing the HTTP response.
Downloaded by Roopa Sk
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb
etc. It is a component based product that lies in the middle-tier of a server centric architecture.
It provides the middleware services for state maintenance and security, along with persistence
and data access. It is a type of server designed to install, operate and host associated services
and applications for the IT services, end users and organizations.
Downloaded by Roopa Sk
Database programming with JDBC: JDBC Drivers, processes with java.sql package
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database.
Downloaded by Roopa Sk
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
i native calls of the database API. It is not written entirely in java.
Downloaded by Roopa Sk
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Downloaded by Roopa Sk
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.
Downloaded by Roopa Sk
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
There are 5 steps to connect any java application with the database using JDBC.
connection JDBC
Database Access
Downloaded by Roopa Sk
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically
load the driver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
Downloaded by Roopa Sk
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException
JDBC was designed to keep simple things simple. This means that the JDBC
API makes everyday database tasks, like simple SELECT statements, very
easy.
Import a package java.sql.* : This package provides you set of all classes that
enables a network interface between the front end and back end database.
• DriverManager will create a Connectionobject.
• java.sql.Connection interface represents a connection with a specific
database. Methods of connection is close(), creatStatement(),
prepareStatement(), commit(), close() and prepareCall()
• Statement interface used to interact with database via the execution of SQL
statements. Methods of this interface are executeQuery(), executeUpdate(),
execute() and getResultSet().
• A ResultSet is returned when you execute an SQL statement. It maintains a
pointer to a row within the tablur results. Mehods of this interface are next(),
getBoolean(), getByte(), getDouble(), getString() close() and getInt().
Connection interface
Downloaded by Roopa Sk
A Connection is a session between a Java application and a database. It helps to establish a
connection with the database.
3) public void setAutoCommit(boolean status): is used to set the commit status. By default,
it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object of
ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
Downloaded by Roopa Sk
4) public int[] executeBatch(): is used to execute batch of commands.
Let9s see the simple example of Statement interface to insert, update and delete the record.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
xe","system","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 w
here id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Downloaded by Roopa Sk
How to get the instance of PreparedStatement?
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)
public void setDouble(int paramIndex, sets the double value to the given parameter
double value) index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.
Downloaded by Roopa Sk
How to get the instance of CallableStatement?
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
2) public boolean previous(): is used to move the cursor to the one row previous from
the current position.
3) public boolean first(): is used to move the cursor to the first row in result set
object.
4) public boolean last(): is used to move the cursor to the last row in result set
object.
5) public boolean absolute(int is used to move the cursor to the specified row number
row): in the ResultSet object.
Downloaded by Roopa Sk
6) public boolean relative(int row): is used to move the cursor to the relative row number in
the ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of
columnIndex): the current row as int.
8) public int getInt(String is used to return the data of specified column name of
columnName): the current row as int.
9) public String getString(int is used to return the data of specified column index of
columnIndex): the current row as String.
10) public String getString(String is used to return the data of specified column name of
columnName): the current row as String.
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata
from the ResultSet object.
Method Description
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
Downloaded by Roopa Sk
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
Example :
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{ Class.forName("oracle.jdbc.driver.OracleDriver"
); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.close();
}catch(Exception e){ System.out.println(e);} }
Downloaded by Roopa Sk
Downloaded by Roopa Sk