AJAVAUnit 5
AJAVAUnit 5
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)
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.
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)
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
2 it is note reserved for windows only you can use separate library for Linux or other machine.
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.
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.
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
2 It is platform independent driver you can use any platform (Windows,Linux,mac) the
driver is same
Disadvantages
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
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.
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
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
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.
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.
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
index.html
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.
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 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 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.
JSP Declarations
JSP Expression
JSP Comments
Control-Flow Statements
Loop Statements