0% found this document useful (0 votes)
7 views

java web UNIT1

The document introduces web-based applications, highlighting their advantages such as cross-platform compatibility, manageability, and cost reduction. It discusses various technologies used in web development, including Progressive Web Apps, micro frontends, and frameworks like Angular and React, as well as Java technologies like Servlets, JSP, and JDBC. Additionally, it covers web architecture models, specifically Model 1 and Model 2 (MVC), detailing their structures and benefits.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

java web UNIT1

The document introduces web-based applications, highlighting their advantages such as cross-platform compatibility, manageability, and cost reduction. It discusses various technologies used in web development, including Progressive Web Apps, micro frontends, and frameworks like Angular and React, as well as Java technologies like Servlets, JSP, and JDBC. Additionally, it covers web architecture models, specifically Model 1 and Model 2 (MVC), detailing their structures and benefits.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT-I

INTRODUCTION TO WEB APPLICATIONS

What is a web-based application?


A web-based application is an application which has the website as the interface (the ‘front-
end’). Users can access the application from any computer connected to the Internet or
Intranet, instead of using an application installed on the stand alone computer. Web-based e-
mail such as Hotmail is one of the best example as a common web-based application that
performs the same functions as a traditional desktop application.
What are the advantages?
1. Cross platform compatibility :
Most web based applications are far more compatible across platforms than traditional
installed software. Typically the minimum requirement would be a web browser of which
there are many. (Internet Explorer, Firefox, Chrome, Safari to name but a few). So whether
you use Windows, Linux or Mac OS you can still run the web application.
2. More manageable :
Web application development systems need only be installed on the server placing minimal
requirements on the end user workstation. Maintaining and updating the system is much
simpler, ny client updates can be deployed via the web server with ease.
3. Highly deployable :
Due to the manageability and cross platform support deploying web applications for any
platform in any type of work environment is easier. It is ideal where bandwidth is limited and
the system and data is remote to the user. At their most deployable you simply need to send
the user a website address to log in to and provide them with internet access. Thus it has huge
implications allowing one to widen access to various systems, streamline processes and
improve relationships by providing access to customers, suppliers and any third parties
4. Secure live data :
Larger and complex systems carry more data and have separate systems and data sources. In
web based systems these systems and processes can often be consolidated by reducing the
need to have separate systems. Web based applications provide an added layer of security by
removing access to the data and back end servers.
5. Reduced costs :
One can dramatically lower costs with the help of Web based applications due to reduced
support and maintenance, lower requirements on the end user system and simplified
architecture. By further streamlining your business operations as a result of your web based
application additional savings can often be found.

Technologies used

1.PROGRESSIVE WEB APPS (PWA)

The progressive web application is a type of application software for the web, built using
technologies such as HTML, CSS, and JavaScript. In simpler terms, a progressive web app is
a website that looks and feels like an app instead of a website. Web users can browse on their
browser with an URL just like every other website; however, they get the experience of using
an “app” without the need to download and install.

PWA is not limited to either PC or mobile, and they can be implemented both on desktops
and mobile devices. To figure out if a website is a PWA, you can access different pages and
see if the pages reload. If they don’t, they are behaving as an app, and they are an example of
PWA. There are many popular PWA that we are currently using daily such as Pinterest, Uber,
Starbucks, and Spotify.
2.MICRO FRONTENDS

A micro-frontend architecture is a design where a frontend app is decomposed into “micro-


apps,” which work loosely together and are independently deployable. Thus, the micro
frontend is the microservices for the front end, which is the user interface of a website or an
app.
As the front end is becoming more and more important than the back end, micro frontends
might be the best solution for websites and web apps that need to be constantly changed and
upgraded without affecting the whole system.
3.FRONTEND FRAMEWORKS

Angular
Angular is a TypeScript-based, open-source, front-end mobile and web application
framework developed by Google in 2010. Angular is a complete rewrite of AngularJS from
the same team. In short, Angular is a platform and framework for building dynamic single-
page client applications through HTML and TypeScript.

Compared to Angular, AngularJS is based on JavaScript and has notions of scope and
controllers instead of a hierarchy of components and services like Angular. AngularJS
follows the MVC (model-view-controller) model, which acts as the central component and
dictates how the applications behave. There is also no mobile support for AngularJS.

Angular is popular due to its ability to create multiple modules for a single web application.
These modules can then act independently, and developers can compile them to create a
single running, dynamic application for end-users. Angular helps developers ensure swift
development and lighter and faster apps due to deleting unnecessary codes.

Since Angular is developed and maintained by Google, there are many resources and
communities that you can learn Angular from and for continuous support and guidance. This
makes Angular one of the top frameworks for your mobile and web app projects.
React
React is an open-source, front-end JavaScript library for creating interactive UIs. React is
developed and maintained by Facebook and a large community of dedicated developers.
React can also be used as a base for a single-page or mobile application.

React is based on the MVVM (Model-View-ViewModel) pattern, which ultimately allows


the view and model to communicate directly with each other. This enables React to break
down the app into modular, single-purpose components that are more complex for your
applications.

React is for websites (front-end), while React Native is for mobile applications, including
iOS and Android. Based on React, React Native helps developers produce mobile apps cross-
platform with simplicity and flexibility.

React is still one of the most popular JavaScript front-end frameworks despite being a library
due to its clean programming, strong community, and fast performance.

Technologies used in Java Web Development


1. Java Servlet API

Java Servlet is Java's first-ever server-side web technology that enables you to define HTTP-
specific classes. The servlet class expands the power and capability of the servers and hosts
the application. These applications can be accessed with the request-response editing model.

Although a servlet can respond to any request, the main purpose of using a servlet is to
extend applications hosted by web servers. For example, you can use servlets to get data
input from an online application or even extend it to appear on the screen or an HTML page.
Additionally, you can use the servlet to write data to a database or file. The servlet works on
the server-side with no application GUI or HTML.

2. Java Server Pages Technology

Java Server Pages (JSP) technology is very popular among developers and provides an easy
and fast way to improve dynamic web content. It leads to the rapid development of web
platforms and standalone web applications. Additionally, you can add a snippet of servlet
code to the text document of the app, making JSP friendly to the developer. Also, JSP pages
are text-based documents that include two types of text:

Static Data that can be expressed in any text format, including XML, HTML, or WML. JSP
Technology fully determines dynamic content creation on a web page.

The packages used for JSP page building are javax.servlet.jsp, javax.el,
javax.servlet.jsp.tagexta, and javax.servlet.jsp.el. However, you will need to import them
directly. With JSP, it can be very easy to create a web application with snipped JSP code and
extensions.

You can develop a website with JSP technology pages by using single captions and inserting
them into the header.html file that describes site navigation. To make changes to buttons or
links, you need to make changes to one file, and it will be automatically redirected all over
the site.

Because of this, the Java program development company claims that JSP is the best
technology for creating powerful web contents such as forms, surveys, and more.

JavaServer Pages Standard Tag Library

The JavaServer Pages Standard Tag Library (JSTL) integrates core functionality common to
many JSP-based applications. Instead of mixing tags from multiple vendors in your
applications, you are using one common set of tags. This configuration allows you to run
your applications on any JSP container that supports JSTL and makes it more likely that the
tag implementation will be improved.

JSTL has duplicate tags and conditional tags to control flow controls, XML document
deciphering tags, global tags, website access tags using SQL, and commonly used function
tags. The packages you can access using JSTL are javax.servlet.jsp.jstl.core,
javax.servlet.jsp.jstl.fmt, javax.servlet.jsp.jstl.sql, and javax.servlet.jsp.jstl. tlv.

3. JavaServer Faces Technology


JavaServer Faces Technology (JSF) is a UI framework that allows you to create web
applications. The GUI component framework is one of the main components of JavaServer
Faces technology that renders the components in a variety of mark-up languages and other
technologies. It also has RenderKit for creating HTML mark-ups. Java APIs and XML
configuration files enable this functionality. In addition, its GUI drag and drop tools in Sun
Java Studio Creator IDE help to use technology without writing or understanding parts of the
code.

4. JDBC API

The Java Database Connectivity (JDBC) API is very popular, and most developers
understand how important JDBC is for web application development as it allows you to
request SQL database commands within Java applications. Additionally, there are no special
restrictions involved, as you can request JDBC API in servlet, JSP pages, or enterprise beans.
JDBC comprises two components, one application-level interface and another service
provider interface. An application-level interface is used to access the database through
application components, and the server provider integrates the JDBC driver into the Java
enterprise platform.

5. Java Message Service API

You already know the importance of sending messages, whether between people or parts of
software or applications. Throughout the software program, the messaging system is peer-to-
peer-centric. In short, the messaging client sends a message to the recipient client and
receives messages from other clients.

In this, each client connects to a message agent that assists in creating, sending, receiving,
and reading the message. The Java Messaging Service API is a Java technology platform that
solves the problem of communication between clients and achieves its purpose. Enterprise
messaging offers a flexible, reliable way of data exchange throughout the business. The JMS
API extends this functionality and adds to the provider framework to provide the
development of portable messaging applications in the Java language. Additionally, how you
will be using the JMS is a matter of perception. One way is to use it to maintain innovative
monitoring.

6. Java API for XML processing

XML (Extensible Markup Language) processing is an important process in Java web


development. The Java API for XML Processing (JAXP) supports it using the Document
Object Model (DOM), the Simple API for XML (SAX), and XSLT API (Extensible
Stylesheet Language Transformation). JAXP provides application analysis and conversion of
XML documents without any XML processing functionality.

It also provides namespace support that allows your application to work with conflicting
word schemes. It is highly customizable, allows you to use XML and XSL compliant
processors in your application, and supports the W3C schema.
7. Java Naming and Directory Interface (JNDI)

As the name elevates itself, it provides naming and directory features, enabling apps to access
multiple naming services and directory services. In addition, it provides applications with
methods that can perform common directory operations such as object search, attribute
association, and more. In addition, using the JNDI, various types of named Java technology
objects can be stored and retrieved, allowing applications to co-exist with many legacy
applications and systems. Access to the JNDI naming environment is provided by Naming
services to application clients, web components, and enterprise beans.

Additionally, developers can customize the components using a naming environment without
changing or accessing the source code of the component.

8. Java Persistence API

The Java Persistence API (JPA) uses an object-relational mapping to link an object-oriented
model to a database. Relational data in Java applications can be easily managed with Java
Persistence. It helps to store or retrieve large amounts of data from the database on a
continuous basis.

You do not have to use excess of codes, proprietary frameworks, etc. In order to connect to
the site, JPA will provide you with an easy way to communicate with the site using an object
relational approach. JPA is a collection of effective classes and methods that can connect you
to a database.

9. JavaMail API and the JavaBeans Activation Framework

Web applications can use the JavaMail API to send email notifications. The API consists of
two parts: the application-level interface used by the program components to send an email
and the service provider's interface. Service providers use some email protocols, such as
SMTP (Simple Mail Transfer Protocol). Several service providers are included with the
JavaMail API package, and some are available separately. The Java EE forum includes a
JavaMail extension with a service provider that allows parts of the application to send email.

By integrating with the JavaMail extension, you can use the JavaBeans Activation
Framework (JAF) API. This API provides standard services to determine the type of incorrect
data, compile access to it, locate the services available to it, and create an appropriate
component based on the creation of a JavaBeans component (JavaBeans component) to
perform those tasks.

Other Java Technologies

You might want to consider using the following other technologies in your web application,
depending on the application's complexity:
J2EE Connector Architecture: Tool vendors and system integrators use this platform to
create service adapters that support access to business information systems that can be linked
to any product based on Java EE technology.

Java Authentication and Authorization Service (JAAS): JAAS provides an application


based on Java EE technology to authenticate and authorize a specific user or group of users to
implement it.

Java API for XML Registries (JAXR): JAXR allows you to access business registrations
and general purposes on the web.

Java Architecture for XML Binding (JAXB): JAXB provides an easy way to integrate
XML schema into a representation in applications written in Java programming language.

SOAP with Attachments API for Java (SAAJ): SAAJ is a low-level API on which JAX-
WS and JAXR rely.

Java Transaction API (JTA): JTA provides a standard visual interface for designing tasks.

Java Beans: JavaBeans classes combine several elements into one component known as a
bean. JavaBean is a class that should be serializable, have a no argument constructor, and
should also provide methods for setting or acquiring property values.

Net Beans IDE: NetBeans is an open source, free integrated development platform for web,
mobile or desktop applications using Java. It provides complete integrated support for the
development cycle namely from creation to profiling, error correction and deployment.

Web Architecture Models

Before developing the web applications, we need to have idea about design models. There are
two types of programming models (design models)

1. Model 1 Architecture
2. Model 2 (MVC) Architecture

Model 1 Architecture

Servlet and JSP are the main technologies to develop the web applications.

Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it
creates thread to handle request. The advantage of creating thread over process is that it
doesn't allocate separate memory area. Thus many subsequent requests can be easily handled
by servlet.

Problem in Servlet technology Servlet needs to recompile if any designing code is modified.
It doesn't provide separation of concern. Presentation and Business logic are mixed up

JSP overcomes almost all the problems of Servlet. It provides better separation of concern,
now presentation and business logic can be easily separated. You don't need to redeploy the
application if JSP page is modified. JSP provides support to develop web application using
JavaBean, custom tags and JSTL so that we can put the business logic separate from our JSP
that will be easier to test and debug.

As you can see in the above figure, there is picture which show the flow of the model1
architecture.

1. Browser sends request for the JSP page


2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture

o Easy and Quick to develop web application

Disadvantage of Model 1 Architecture

o Navigation control is decentralized since every page contains the logic to determine
the next page. If JSP page name is changed that is referred by other pages, we need to
change it in all the pages that leads to the maintenance problem.
o Time consuming You need to spend more time to develop custom tags in JSP. So
that we don't need to use scriptlet tag.
o Hard to extend It is better for small applications but not for large applications.

Model 2 (MVC) Architecture


Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design
pattern consists of three modules model, view and controller.

Model The model represents the state (data) and business logic of the application.

View The view module is responsible to display data i.e. it represents the presentation.

Controller The controller module acts as an interface between view and model. It intercepts
all the requests i.e. receives input and commands to Model / View to change accordingly.

Advantage of Model 2 (MVC) Architecture

o Navigation control is centralized Now only controller contains the logic to


determine the next page.
o Easy to maintain
o Easy to extend
o Easy to test
o Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture

o We need to write the controller code self. If we change the controller code, we need to
recompile the class and redeploy the application.

Solution of Model 2 Architecture: Configurable MVC Components


It uses the declarative approach for defining view components, request mapping etc. It
resolves the problem of Model 2 architecture. The Struts framework provides the
configurable MVC support. In struts 2, we define all the action classes and view components
in struts.xml file

MVC Architecture

The Model-View-Controller (MVC) is a well-known design pattern in the web development


field. It is way to organize our code. It specifies that a program or application shall consist of
data model, presentation information and control information. The MVC pattern needs all
these components to be separated as different objects.

In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and
disadvantages and examples to understand the implementation of MVC in Java.

The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the
data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.

In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

MVC Architecture Layers

Model Layer

The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and
store the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.

View Layer

As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.

Controller Layer

The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the
controller and then displayed on the view.

Introducing and defining ODBC


ODBC stands for Open Database Connectivity.
It is an open standard Application Programming Interface also known as API which is used
for accessing a database. First ODBC driver was build in 1992 when Microsoft partners
with Simba named SIMBA.DLL. With the help of ODBC statement in a program. We can
access different files in a number of a different or common database.
Components of ODBC :
There are 4 main components of ODBC these are as follows :

1. Application –
This component basically calls ODBC function and submits SQL statements.

2. Driver Manager –
The role of this component is to load driver for each application.

3. Driver –
Role of this component to handle all function calls and then submits each SQL
requests to a data source.
4. Data Source –
Role of this component to access data.

Features of ODBC :
Following are some of features of ODBC :

 Error Codes –
ODBC basically supports error code mechanism to show issues which caused
error to occur while processing SQL statements.

 Attributes –
Beside Error Code feature it also provides different types of functions to get
details of attributes and functions that are used in drivers.

 Rich metadata –
ODBC also provides huge support to data about data also known as metadata.
ODBC also provides different functions to get data about both functions and
data types used.

 Inter-operability –
The most important feature of ODBC is its interoperability that means using
ODBC driver we can develop different applications that can communicate with
different DB also known as Database Management System and switching our
application from one database to another will not create any problem.

 SQL Syntax –
ODBC basically implements SQL syntax for easy understanding of user because
SQL syntax are easily understood by end-user. Whenever an SQL statement is
passed by user to ODBC driver it matches given statement to SQL 92 standard
and converts it into respective SQL statement that is accepted by an underlying
database.
1. It is well integrated into many different RAD tools.

2. It interfaces easily into a variety of “data-bound” components in


different development environments such as Powerbuilder, Delphi,
Visual Basic and Java etc.

3. It basically simplifies and also speeds up application development.

4. It also helps to edit multiple different objects at a time, with the help
of templates provided by ODBC.

5. It also allows maximum interoperability that basically means that a


single application can easily access different database management
systems or we can also say ODBC permits a single application to
handle different types of DBMS based on user requirement or type of
DBMS available.
6. With the help of built-in function we can create custom applications.

Disadvantages of ODBC:
Despite having lots of advantages and features ODBC also posses some disadvantages too
these are as follows :
1. Slow with large databases –
As the size of databases increase speed of ODBC reduces.

2. Servers not standardized –


In ODBC since most of work is done by clients or User, it is very difficult to
scale and also these ODBC drivers are also not standardized. Because of which
clients maintain their own driver, naming tables which creates a problem for
management of large sites.

3. Complicated to build –
These ODBC drivers are complicated to build and also complicated to maintain.

4. Depends on framework –
As ODBC specification specifies only application protocol so it basically
inherits features of framework in which it is used on. Thus we can say that
reliability depends on implementation of request/response protocol of underlying
framework that is being used.

Working with JDBC API’S

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

API

API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of thin driver.
2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

3) Network Protocol driver

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.
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.

Java Database Connectivity


1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections

Step 1: Import the Packages


Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
 user: Username from which your SQL command prompt can be accessed.
 password: password from which the SQL command prompt can be accessed.
 con: It is a reference to the Connection interface.
 Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before
calling the function. Use of this can be referred to from the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to
send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:
 The query for updating/inserting a table in a database.
 The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can be
used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries
of updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Example Java Program
import java.sql.*;
// Importing required classes
import java.util.*;

// Main class
class Main {

// Main driver method


public static void main(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Username and password to access DB


// Custom initialization
String user = "system";
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);

System.out.println("enter name");
String name = k.next();

System.out.println("enter roll no");


int roll = k.nextInt();

System.out.println("enter class");
String cls = k.next();

// Inserting data using SQL query


String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

// Try block to check for exceptions


try {
// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,
pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");

// Closing the connections


con.close();
}

// Catch block to handle exceptions


catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

JDBC(Java Database Connectivity)


JDBC is an API(Application programming interface) used in java programming to interact
with databases. The classes and interfaces of JDBC allow the application to
send requests made by users to the specified database.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with
databases to store application-specific information. So, interacting with a database requires
efficient database connectivity, which can be achieved by using the ODBC(Open database
connectivity) driver. This driver is used with JDBC to interact or communicate with various
kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.

Components of JDBC
There are generally four main components of JDBC through which it can interact with a
database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
2. It also provides a standard to connect a database to a client application.
3. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.

4. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation)
being performed by JDBC Drivers.
5. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of
the sun.jdbc.odbc package which includes a native library to access ODBC characteristics.

Architecture of JDBC

1. Application: It is a java applet or a servlet that communicates with a data


source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and interfaces
defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses
some database-specific drivers to effectively connect enterprise applications to
databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access a
database. They are as described below:

1. Two-tier model: A java application communicates directly to the data source.


The JDBC driver enables the communication between the application and the
data source. When a user sends a query to the data source, the answers for those
queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a
user is connected. This is known as a client/server configuration, where the
user’s machine acts as a client, and the machine has the data source running acts
as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services,
from which the commands are again sent to the data source. The results are sent
back to the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using
JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be
added in java application for JDBC support which can be done dynamically at run time.
This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application

package com.vinayak.jdbc;

import java.sql.*;

public class JDBCDemo {

public static void main(String args[])


throws SQLException, ClassNotFoundException
{
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query
= "insert into students values(109, 'bhatt')";

// Load driver class


Class.forName(driverClassName);

// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);

// Obtain a statement
Statement st = con.createStatement();

// Execute the query


int count = st.executeUpdate(query);
System.out.println(
"number of rows affected by this query= "
+ count);

// Closing the connection as per the


// requirement with connection is completed
con.close();
}
}

The above example demonstrates the basic steps to access a database using JDBC. The
application uses the JDBC-ODBC bridge driver to connect to the database. You must
import java.sql package to provide basic SQL functionality and use the classes of the
package.

JDBC Statement:

java.sql.Statement is an interface. It provides some methods through which we can submit


SQL queries to the database. It will be implemented by driver implementation providers.
createStatement() method on Connection object will return Statement object.

JDBC ResultSet:

java.sql.ResultSet also an interface and is used to retrieve SQL select query results. A
ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is
positioned before the first row. The next method moves the cursor to the next row, and
because it returns false when there are no more rows in the ResultSet object, it can be used in
a while loop to iterate through the result set. It provides getXXX() methods to get data from
each iteration. Here XXX represents datatypes.

Types of Statements in JDBC

The statement interface is used to create SQL basic statements in Java it provides methods
to execute queries with the database. There are different types of statements that are used in
JDBC as follows:
 Create Statement
 Prepared Statement
 Callable Statement
1. Create a Statement: From the connection interface, you can create the object for this
interface. It is generally used for general–purpose access to databases and is useful while
using static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
 boolean execute(String SQL): If the ResultSet object is retrieved, then it returns
true else false is returned. Is used to execute SQL DDL statements or for
dynamic SQL.
 int executeUpdate(String SQL): Returns number of rows that are affected by
the execution of the statement, used when you need a number for INSERT,
DELETE or UPDATE statements.
 ResultSet executeQuery(String SQL): Returns a ResultSet object. Used
similarly as SELECT is used in SQL.

import java.sql.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Try block to check if any exceptions occur
try {

// Step 2: Loading and registering drivers

// Loading driver using forName() method


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 3: Create a statement


Statement statement = con.createStatement();
String sql = "select * from people";

// Step 4: Execute the query


ResultSet result = statement.executeQuery(sql);

// Step 5: Process the results

// Condition check using hasNext() method which


// holds true till there is single element
// remaining in List
while (result.next()) {

// Print name an age


System.out.println(
"Name: " + result.getString("name"));
System.out.println(
"Age:" + result.getString("age"));
}
}

// Catching database exceptions if any


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catching generic ClassNotFoundException if any


catch (ClassNotFoundException e) {

// Print and display the line number


// where exception occurred
e.printStackTrace();
}
}
}

2. Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED
STATEMENT at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ?
holders, setXXX() of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name
 execute(): This returns a boolean value and executes a static SQL statement that
is present in the prepared statement object.
 executeQuery(): Returns a ResultSet from the current prepared statement.
 executeUpdate(): Returns the number of rows affected by the DML statements
such as INSERT, DELETE, and more that is present in the current Prepared
Statement.

import java.sql.*;
// Importing Scanner class to
// take input from the user
import java.util.Scanner;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// try block to check for exceptions
try {

// Step 2: Establish a connection

// Step 3: Load and register drivers


// Loading drivers using forName() method
Class.forName("com.mysql.cj.jdbc.Driver");

// Scanner class to take input from user


Scanner sc = new Scanner(System.in);

// Display message for ease for user


System.out.println(
"What age do you want to search?? ");

// Reading age an primitive datatype from user


// using nextInt() method
int age = sc.nextInt();

// Registering drivers using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 4: Create a statement


PreparedStatement ps = con.prepareStatement(
"select name from world.people where age = ?");

// Step 5: Execute the query


ps.setInt(1, age);
ResultSet result = ps.executeQuery();

// Step 6: Process the results

// Condition check using next() method


// to check for element
while (result.next()) {

// Print and display elements(Names)


System.out.println("Name : "
+ result.getString(1));
}

// Step 7: Closing the connections


// (Optional but it is recommended to do so)
}

// Catch block to handle database exceptions


catch (SQLException e) {

// Display the DB exception if any


System.out.println(e);
}
// Catch block to handle class exceptions
catch (ClassNotFoundException e) {

// Print the line number where exception occurred


// using printStackTrace() method if any
e.printStackTrace();
}
}
}

3. Callable Statement are stored procedures which are a group of statements that we
compile in the database for some task, they are beneficial when we are dealing with
multiple tables with complex scenario & rather than sending multiple queries to the
database, we can send the required data to the stored procedure & lower the logic executed
in the database server itself. The Callable Statement interface provided by JDBC API helps
in executing stored procedures.
Syntax: To prepare a CallableStatement

CallableStatement cstmt = con.prepareCall("{call Procedure_name(?,?}");

 execute() is used to perform the execution of the statement.

import java.sql.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Try block to check if any exceptions occurs
try {

// Step 2: Establish a connection

// Step 3: Loading and registering drivers

// Loading driver using forName() method


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 4: Create a statement


Statement s = con.createStatement();

// Step 5: Execute the query


// select * from people

CallableStatement cs
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");

// Step 6: Process the results

// Condition check using next() method


// to check for element
while (result.next()) {

// Print and display elements (Name and Age)


System.out.println("Name : "
+ result.getString(1));
System.out.println("Age : "
+ result.getInt(2));
}
}

// Catch statement for DB exceptions


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catch block for generic class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occurred


e.printStackTrace();
}
}
}
JDBC - Result Sets

The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a
result set. The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
 Navigational methods − Used to move the cursor around.
 Get methods − Used to view the data in the columns of the current row being
pointed by the cursor.
 Update methods − Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are
designated when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet

 createStatement(int RSType, int RSConcurrency);
 prepareStatement(String SQL, int RSType, int RSConcurrency);
 prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of
two ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the


result set.

ResultSet.TYPE_SCROLL_INSENSITIV The cursor can scroll forward and backward,


E and the result set is not sensitive to changes
made by others to the database that occur
after the result set was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward,


and the result set is sensitive to changes
made by others to the database that occur
after the result set was created.

Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

Navigating a Result Set


There are several methods in the ResultSet interface that involve moving the cursor,
including −

S.N. Methods & Description

1 public void beforeFirst() throws SQLException


Moves the cursor just before the first row.

2 public void afterLast() throws SQLException


Moves the cursor just after the last row.

3 public boolean first() throws SQLException


Moves the cursor to the first row.

4 public void last() throws SQLException


Moves the cursor to the last row.

5 public boolean absolute(int row) throws SQLException


Moves the cursor to the specified row.

6 public boolean relative(int row) throws SQLException


Moves the cursor the given number of rows forward or backward, from where it is
currently pointing.

7 public boolean previous() throws SQLException


Moves the cursor to the previous row. This method returns false if the previous
row is off the result set.

8 public boolean next() throws SQLException


Moves the cursor to the next row. This method returns false if there are no more
rows in the result set.

9 public int getRow() throws SQLException


Returns the row number that the cursor is pointing to.

10 public void moveToInsertRow() throws SQLException


Moves the cursor to a special row in the result set that can be used to insert a new
row into the database. The current cursor location is remembered.

11 public void moveToCurrentRow() throws SQLException


Moves the cursor back to the current row if the cursor is currently at the insert
row; otherwise, this method does nothing

Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(QUERY);
){
// Move cursor to the last row.
System.out.println("Moving cursor to the last...");
rs.last();

// Extract data from result set


System.out.println("Displaying record...");
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);

// Move cursor to the first row.


System.out.println("Moving cursor to the first row...");
rs.first();

// Extract data from result set


System.out.println("Displaying record...");
// Retrieve by column name
id = rs.getInt("id");
age = rs.getInt("age");
first = rs.getString("first");
last = rs.getString("last");

// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
// Move cursor to the first row.

System.out.println("Moving cursor to the next row...");


rs.next();

// Extract data from result set


System.out.println("Displaying record...");
id = rs.getInt("id");
age = rs.getInt("age");
first = rs.getString("first");
last = rs.getString("last");

// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);

} catch (SQLException e) {
e.printStackTrace();
}
}
}
Viewing a Result Set
The ResultSet interface contains dozens of methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two
versions −
 One that takes in a column name.
 One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one
of the getInt() methods of ResultSet −

S.N Methods & Description


.

1 public int getInt(String columnName) throws SQLException


Returns the int in the current row in the column named columnName.

2 public int getInt(int columnIndex) throws SQLException


Returns the int in the current row in the specified column index. The column index starts
at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.

Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
Updating a Result Set
The ResultSet interface contains a collection of update methods for updating the data of a
result set.
As with the get methods, there are two update methods for each data type −
 One that takes in a column name.
 One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one
of the following updateString() methods −

S.N. Methods & Description

1 public void updateString(int columnIndex, String s) throws SQLException


Changes the String in the specified column to the value of s.

2 public void updateString(String columnName, String s) throws SQLException


Similar to the previous method, except that the column is specified by its name instead
of its index.

There are update methods for the eight primitive data types, as well as String, Object, URL,
and the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet
object, but not in the underlying database. To update your changes to the row in the database,
you need to invoke one of the following methods.

S.N Methods & Description


.

1 public void updateRow()


Updates the current row by updating the corresponding row in the database.

2 public void deleteRow()


Deletes the current row from the database

3 public void refreshRow()


Refreshes the data in the result set to reflect any recent changes in the database.

4 public void cancelRowUpdates()


Cancels any updates made on the current row.

5 public void insertRow()


Inserts a row into the database. This method can only be invoked when the cursor is
pointing to the insert row.

You might also like