0% found this document useful (0 votes)
12 views23 pages

AJAVAUnit 5

JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with various relational databases through executing SQL queries. It consists of components such as the JDBC API, DriverManager, JDBC drivers, and a test suite, and supports both 2-tier and 3-tier architectures. There are four types of JDBC drivers (Type 1 to Type 4), each with its own advantages and disadvantages, with Type 4 being the most commonly recommended for single database applications.

Uploaded by

solankiaryamann2
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)
12 views23 pages

AJAVAUnit 5

JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with various relational databases through executing SQL queries. It consists of components such as the JDBC API, DriverManager, JDBC drivers, and a test suite, and supports both 2-tier and 3-tier architectures. There are four types of JDBC drivers (Type 1 to Type 4), each with its own advantages and disadvantages, with Type 4 being the most commonly recommended for single database applications.

Uploaded by

solankiaryamann2
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/ 23

Unit-V

What is JDBC

JDBC stands for Java Database Connectivity is a Java API(Application Programming Interface)
used to interact with databases. JDBC is a specification from Sun Microsystems and it is used by
Java applications to communicate with relational databases. We can use JDBC to execute queries
on various databases and perform operations like SELECT, INSERT, UPDATE and DELETE.

JDBC API helps Java applications interact with different databases like MSSQL,
ORACLE, MYSQL, etc. It consists of classes and interfaces of JDBC that allow the
applications to access databases and send requests made by users to the specified 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.
The java.sql package contains interfaces and classes of JDBC API.

2. java.sql: This package provides APIs for data access and data process in a relational
database, included in
Java Standard Edition (java SE)

javax.sql: This package extends the functionality of java package by providing


datasource interface for
establishing connection pooling, statement pooling with a data source,
included in
Java Enterprise Edition (java EE)
It also provides a standard to connect a database to a client application.

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

3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being
performed by JDBC Drivers.

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

Description:
1. Application: Applications in JDBC architecture are java applications like applets or servlet
that communicates with databases..
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.

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


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.

JDBC Drivers
To convert Java calls to Database specific calls and Database specific to Java calls some
translator must be required and that are known as driver.
There are four types of JDBC drivers defined by Sun Microsystem that are mentioned below:
Type-1 driver(JDBC-ODBC bridge driver or bridge driver)
Type-2 driver(Native-API partly Java driver or Native driver)
Type-3 driver(All java net protocol driver or Network Protocol driver or middleware driver)
Type-4 driver(Pure java driver or native protocol driver or Thin driver)

1. – Type 1 driver -JDBC-ODBC bridge driver


Type-1 driver converts JDBC calls to ODBC calls and ODBC calls to JDBC calls. It is known
as JDBC-ODBC bridge driver. ODBC driver converts ODBC calls into database calls.
It is provided by sun micro system as the part of JDK so no need to install separately.
Internally type1 driver uses ODBC support.

Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver because it is not communicating directly to database.
Disadvantages
 Slowest driver because of two times call conversion.
 The ODBC bridge driver is needed to be installed in individual client machines.
 ODBC driver concept is applicable only for windows machine so for machine like Linux it
is not possible to use so platform independent nature is not with this driver(applicable only
for windows machine so java platform independent nature will missing if you are using this
driver.
 It is available until JDK1.7 version only.
 It is not recommended to use.
2. – Type 2 driver

Native libraries are functions that are developed in non java mostly c and c++.database vendor
is responsible to provide native libraries. These libraries should be installed in the client
machine.
Advantages

1 No odbc driver requirement

2 it is note reserved for windows only you can use separate library for Linux or other machine.

3 Relatively fast as compare to Type1

4 Portability is more.

Disadvantages

1 It is database and platform dependant driver. You have to change driver for different
databases(Oracle/MySql etc) and platform(Windows/Linux etc).

2 It is not recommended.

3 It is not guaranteed that every vendor (Oracle/MySql etc) will provide native libraries.

These libraries are available for oracle(OCI ) not for MySql.

Note: For Type 2 driver in oracle database OCI driver and libraries(c functions) are available
in ODBC14.jar file(for Oracle 10g which uses java1.4 version), ODBC6.jar file( for Oracle
11g which uses java6 version), ODBC7.jar( for Oracle 12c which uses java7 version).You
have to set this jar file in class path. When you will install Oracle these file will get installed by
default.

Type 2 driver is only available for Oracle database not for MySql.

Type 3 driver

In Enterprise applications the most commonly used driver is type3 driver. This driver uses
Middleware (IDS server) to communicate with database.

Advantages

1 It is platform and database independent driver out of all 4 drivers. It is the only driver which
follows 3 tire architecture (type1, 2, 4 are follows 2 tier architecture) .

2 Type-3 drivers are fully written in Java, hence they are portable drivers.

3 Switch facilities to switch over from one database to another database

Disadvantages
1 Network support is required on client machine.
2 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

Type 4 Driver

This driver directly communicated with the database( without any extra components) by
using database specific native protocols provided by database vendors.It converts JDBC
calls into database calls directly. it is also known as pure java driver it is completely
developed in java only. It is also known as native protocol driver.
It is known as thin driver because not required any extra components to work with data
base. It uses vendor specific native protocol to communicate with database hence have
more security.

The most commonly used driver in our application is Type4 driver. Because we are using
only one database.

Advantages

1 Performance is high because of only one level of conversion(JDBC calls to database


calls) is required.

2 It is platform independent driver you can use any platform (Windows,Linux,mac) the
driver is same

3 Not required ODBC, native libraries or middleware server.

4 It is fully written in Java language, hence they are portable drivers.

Disadvantages

The only disadvantage is that It is database dependant driver because of directly


interact with database. If the database varies, then the driver will carry because it is
database dependent.

Ex. Oracle provides Thin driver.MySql provides Connector/J Type4 driver.


Which Driver you should use

Type 4 driver:If you are using only one database that will never change then this driver is
recommended.eg standalone applications or small web applications

Type 3 driver:If you are working with multiple databases like enterprise applications

Ex. large scale web applications and enterprise applications

Type 2:If type 3 and 4 are not available then can go with this.

Type 1:If all other are not available then it can be used.

What are the main classes and interfaces of JDBC?


Class/interface Description

DriverManager This class manages the JDBC drivers. You need to register your drivers to this.
It provides methods such as registerDriver() and getConnection().

Driver This interface is the Base interface for every driver class i.e. If you want to create a
JDBC Driver of your own you need to implement this interface. If you load a Driver
class (implementation of this interface), it will create an instance of itself and register
with the driver manager.

Statement This interface represents a static SQL statement. Using the Statement object and its
methods, you can execute an SQL statement and get the results of it.
It provides methods such as execute(), executeBatch(), executeUpdate() etc. To
execute the statements.

Connection This interface represents the connection with a specific database. SQL statements are
executed in the context of a connection.
This interface provides methods such as close(), commit(), rollback(),
createStatement(), prepareCall(), prepareStatement(), setAutoCommit()
setSavepoint() etc.

ResultSet This interface represents the database result set, a table which is generated by
executing statements. This interface provides getter and update methods to retrieve
and update its contents respectively.

ResultSetMetaDataThis interface is used to get the information about the result set such as, number of
columns, name of the column, data type of the column, schema of the result set, table
name, etc
It provides methods such as getColumnCount(), getColumnName(),
getColumnType(), getTableName(), getSchemaName() etc.
Class/interface Description

DriverManager This class manages the JDBC drivers. You need to register your drivers to this.
It provides methods such as registerDriver() and getConnection().

Driver This interface is the Base interface for every driver class i.e. If you want to create a
JDBC Driver of your own you need to implement this interface. If you load a Driver
class (implementation of this interface), it will create an instance of itself and register
with the driver manager.

Statement This interface represents a static SQL statement. Using the Statement object and its
methods, you can execute an SQL statement and get the results of it.
It provides methods such as execute(), executeBatch(), executeUpdate() etc. To
execute the statements.

Connection This interface represents the connection with a specific database. SQL statements are
executed in the context of a connection.
This interface provides methods such as close(), commit(), rollback(),
createStatement(), prepareCall(), prepareStatement(), setAutoCommit()
setSavepoint() etc.

ResultSet This interface represents the database result set, a table which is generated by
executing statements. This interface provides getter and update methods to retrieve
and update its contents respectively.

ResultSetMetaDataThis interface is used to get the information about the result set such as, number of
columns, name of the column, data type of the column, schema of the result set, table
name, etc
It provides methods such as getColumnCount(), getColumnName(),
getColumnType(), getTableName(), getSchemaName() etc.
Connection with MySql server

Steps to work with JDBC

1 Download driver software for related database

2 Register it with driver manager

3 Create connection with database

4 Execute query

Example

import java.sql.*;
class Database
{
public static void main(String[] args)
{
Connection con =null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
System.out.println("Xampp mysql connected..");
Statement st = con.createStatement();
String query = "select * from studentinfo";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
System.out.println(rs. getInt (1)+" "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}

}
javac -cp mysql-connector-j-8.4.0.jar;. Database.java
java -cp mysql-connector-j-8.4.0.jar;. Database

JDBC program to perform Select, Insert, Update and Delete query


import java.sql.*;
import java.io.*;
class Database
{
public static void main(String[] args)
{
int sroll;
String sname;
String query;
int result;
Connection con =null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
System.out.println("Xampp mysql connected..");
Statement st = con.createStatement();
System.out.println("Enter your choice 1:Select,2:Insert,3:Update,4:Delete ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int choice=Integer.parseInt(reader.readLine());
switch(choice)
{
case 1:
query = "select * from studentinfo";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
//System.out.println(rs.getInt("SRoll")+" "+rs.getString("Sname"));
}
break;
case 2:
System.out.println(" Enter Roll Number and Name");
sroll=Integer.parseInt(reader.readLine());
sname=reader.readLine();
query="insert into studentinfo(SRoll,Sname) values("+sroll+",'"+sname+"')";
result = st.executeUpdate(query);
if (result > 0)
System.out.println("successfully inserted");
else
System.out.println( "unsucessful insertion ");
break;
case 3:
System.out.println("Enter Roll number to update data");
sroll=Integer.parseInt(reader.readLine());
System.out.println("Enter new data");
sname=reader.readLine();
query="update studentinfo set Sname='"+sname+"' where SRoll="+sroll+" ";
result =st.executeUpdate(query);
if (result > 0)
System.out.println("updated successfully");
else
System.out.println( "update unsucess ");
break;
case 4:
System.out.println("Enter Roll number to update data");
sroll=Integer.parseInt(reader.readLine());
query="delete from studentinfo where SRoll="+sroll+" ";
result =st.executeUpdate(query);
if (result > 0)
System.out.println("Deleted successfully");
else
System.out.println( "Delete unsucess ");
break;
default:System.out.println(" wrong selection");

con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}

What is Servlet Life Cycle? Create a servlet application to display‘Welcome to the world of
Servlet’.
What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any
Servlet.
o Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page

Types of Servlet
 Generic Servlets: These are those servlets that provide functionality for implementing a
servlet. It is a generic class from which all the customizable servlets are derived. It is protocol-
independent and provides support for HTTP, FTP, and SMTP protocols. The class used is
‘javax.servlet.Servlet’ and it only has 2 methods – init() to initialize & allocate memory to the
servlet and destroy() to deallocate the servlet.
 HTTP Servlets: These are protocol dependent servlets, that provides support for HTTP request
and response. It is typically used to create web apps. And has two of the most used methods –
doGET() and doPOST() each serving their own purpose.

Components of Servlet Architecture


Servlet Architecture contains the business logic to process all the requests made by client. Below is the high-level
architecture diagram of servlet. Let’s see in brief, how does each component add to the working of a servlet.
1. Client
The client shown in the architecture above is the web browser and it primarily works as a medium
that sends out HTTP requests over to the web server and the web server generates a response
based on some processing in the servlet and the client further processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a user sends over time and maintain
how a web user would be able to access the files that has been hosted over the server. The server we are talking
about here is a software which manages access to a centralized resource or service in a network.
3. Web Container
Web container is another typical component in servlet architecture which is responsible for communicating with the
servlets. Two prime tasks of a web container are:
 Managing the servlet lifecycle
 URL mapping
Web container sits at the server-side managing and handling all the requests that are coming in either from the
servlets or from some JSP pages or potentially any other file system.

How does a Servlet Request flow?


Every servlet should override the following 3 methods namely:
1. init(): To initalize/instantiate the servlet container.
2. service(): This method acts like an intermediatory between the HTTP request and the business logic to serve
that particular request.
3. destroy(): This method is used to deallocate the memory allocated to the servlet.

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new
state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready
state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end
state.
Steps to run servlet
1 Create project folder inside \tomcat\webapps

2 Inside project folder create index.html file,java file and WEB-INF folder
3 Inside WEB-INF create classes folder ,lib folder and web.xml file

4 Write java file code


MyServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome Hari Mohan to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

5Write web logic in web.xml file


<web-app>
<servlet>
<servlet-name>harimohan</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>harimohan</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
6 search for servlet-api.jar file and copy the path to set classpath in environment variable

7 Test for tomcat is running properly,the output should be as


8 Test for index.html file

index.html

9 Compile Java file as


The .class file will be created inside WEB-INF>classes folder

10 Run Servlet application as

What is JSP?
JavaServer Pages (JSP) is a technology that helps developers create dynamic, data-driven web pages. JSP pages are
compiled into Java servlets and run on the server.

JSP uses a special syntax that embeds snippets of Java code within HTML, and these pages are stored as regular
HTML files with a .jsp extension. This code is known as a JSP action.

JSP actions are executed when a user requests the page.

These pages are well suited for use in a distributed environment offering a high degree of flexibility.

JSP pages offer many benefits over traditional HTML pages, such as:

 JSP pages can be easily created and maintained.


 JSP is capable of producing dynamic content, but HTML is not.
 JSP provides excellent performance and scalability.
 The separation of visual logic and functionality makes it easier to manage
The JSP architecture consists of three main components:

 The client requests a JSP page.


 The JSP engine processes the JSP page and generates a response.
 The JSP container manages the lifecycle of JSP pages and servlets.

JSP pages are typically used to display data from a database. The JSP engine reads the JSP and
converts it into a servlet. The Servlet then accesses the database and retrieves the data. The data is
then passed to the JSP page, which displays it to the user.

JSP vs Servlet
Servlets are the foundation of JavaServer Pages. Servlet extends the javax.servlet.http.HttpServlet
class and implements the doGet() and doPost() methods.

The doGet() method is invoked by the browser when the user requests a page, and the doPost()
method is invoked when the user submits a form.

There are a few key differences between JSP and servlets that you should be aware of,

 JSP is a technology for dynamically generating web pages, while servlets are technologies for
encoding web page requests and responses.
 JSP pages are compiled into servlets by the web container, while servlets are compiled into
bytecode that can be run on a Java virtual machine.
 Clients can invoke JSP pages directly, while servlets must be invoked indirectly through a web
server.
 In servlet we write HTML code in java program but in JSP we write java program in HTML
code.so jsp used as scripting language inside tages.

Create and run first program in JSP

Create file as

Example 1:

First.jsp

<html>
<head><title>JSP Program</title></head>
<body>
<font size=10><%="Hello JSP" %></font>
<br>
<%out.println("Welcome you all"); %>
</body>
</html>
Start tomcat server and Run as

Example 2:

Add.jsp

<html>
<head>
<title>Declaration</title>
</head>
<body>
<h3>--Welcome--</h3>
<h3>Use of Declaration in JSP</h3>
<%!int num1 = 10, num2 = 20, n = 0;%>
<%
n = num1 + num2;
out.println("The number after adding declared variables is " + n);
%>
</body>
</html>
Elements/Components of JSP
The Scriptlet

A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet −

<% code fragment %>

JSP Declarations

<%! declaration; [ declaration; ]+ ... %>

JSP Expression

<%= expression %>


<%= (new java.util.Date()).toLocaleString()%>

JSP Comments

<%-- This is JSP comment --%>


<%-- This comment will not be visible in the page source --%>

Control-Flow Statements

<% if (day == 1 || day == 7) { %>


<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>

Loop Statements

<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>


<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy