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

Advanced Java JDBC Tutorial Guide

The document outlines the importance of Advanced Java (JEE) for web application development, highlighting its advantages over Core Java, such as support for Client-Server architecture and various frameworks. It provides an introduction to JDBC (Java Database Connectivity), detailing its architecture, common components, and steps to create a JDBC application. Additionally, it discusses different types of JDBC drivers and connections, emphasizing their roles in database interaction.
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)
10 views23 pages

Advanced Java JDBC Tutorial Guide

The document outlines the importance of Advanced Java (JEE) for web application development, highlighting its advantages over Core Java, such as support for Client-Server architecture and various frameworks. It provides an introduction to JDBC (Java Database Connectivity), detailing its architecture, common components, and steps to create a JDBC application. Additionally, it discusses different types of JDBC drivers and connections, emphasizing their roles in database interaction.
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

Advanced Java Tutorial: Need for Advance

Java
Below I have listed down few major advantages of Advance Java:

1. Advance Java i.e. JEE (Java Enterprise Edition) gives you the library
to understand the Client-Server architecture for Web Application
Development which Core Java doesn’t support.
2. J2EE is platform Independent, Java Centric environment for
developing, building & deploying Web-based applications online. It
also consists of a set of services, APIs, and protocols, which provides
the functionality that is necessary for developing multi-tiered, web-
based applications.
3. You will be able to work with Web and Application Servers like
Apache Tomcat, Glassfish etc and understand the communication
over HTTP protocol. But, in Core Java, it is not possible.
4. There are a lot of Advance Java frameworks like Spring, JSF,
Struts etc. which enable you to develop a secure transaction based
web apps for the domains like E-Commerce, Banking, Legal,
Financial, Healthcare, Inventory etc.
5. To work and understand the hot technologies like Hadoop and
Cloud services, you should be prepared with core and advanced
Java concepts.

I hope you understood why Advanced Java is essential. For your better
understanding, I have divided this article into three sections. Each of
these section deals with one of the most important concepts of advanced
Java:

1. JDBC (Java DataBase Connectivity)


2. Java Servlets
3. JSP (Java Servlet Pages)

So, now let’s begin our discussion and understand the concept of Java
Database Connectivity, a helpful tool to interact with the database.

Advanced Java Tutorial: Introduction to


JDBC
JDBC is a standard Java API for a database-independent connectivity
between the Java programming language and a wide range of
databases. This application program interface lets you encode the access
request statements, in Structured Query Language (SQL). They are then
passed to the program that manages the database. It mainly involves
opening a connection, creating a SQL Database, executing SQL queries
and then arriving at the output.
We can use JDBC API to access tabular data stored in any relational
database. By the help of JDBC API, we can save, update, delete and fetch
data from the databases. It is similar to the Open Database Connectivity
(ODBC) provided by Microsoft.

For a better understanding of working of JDBC, let’s dive deeper into the
topic and understand the architecture that lies behind Java Database
Connectivity.

Advanced Java Tutorial: JDBC Architecture


The JDBC API supports both two-tier and three-tier processing models for
database access but in general, JDBC Architecture consists of two layers −

 JDBC API: This provides the application-to-JDBC Manager


connection.
 JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.

The JDBC API uses a driver manager and database-specific drivers to


provide transparent connectivity to heterogeneous databases. The JDBC
driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases.

Advanced Java Tutorial: Common JDBC Components

The JDBC API provides the following interfaces and classes −

 DriverManager is used to manage a list of database drivers. The


first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
 Driver is an interface that handles the communications with the
database server. It also abstracts the details associated with
working with Driver objects.
 Connection is an interface that consists all the methods required to
connect to a database. The connection object represents
communication context, i.e., all communication with the database is
through connection object only.

Now let’s move on to the next topic and look at the steps required to
create a JDBC Application.

Advanced Java Tutorial: Steps to create


JDBC Application
In order to create JDBC Application, we need to follow few steps. Let’s see
what are they.

1. Import the packages: You need to include the packages


containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
2. Register the JDBC driver: Here you have to initialize a driver so
that you can open a communication channel with the database.
3. Open a connection: Here, you can use
the getConnection() method to create a Connection object, which
represents a physical connection with the database.
4. Execute a query: Requires using an object of type Statement for
building and submitting an SQL statement to the database.
5. Extract data from result set: Requires that you use the
appropriate getXXX() method to retrieve the data from the result
set.
6. Clean up the environment: Requires explicitly closing all
database resources versus relying on the JVM’s garbage collection.

Now as you have seen various steps involved to create a JDBC Application,
let’s see an example code to create a database and establish a
connection.

1package Edureka;
2import [Link].*;
3import [Link];
4public class Example {
5// JDBC driver name and database URL
6static final String JDBC_DRIVER = "[Link]";
7static final String DB_URL = "jdbc:mysql://localhost/emp";
8// Database credentials
static final String USER = "root";
9
static final String PASS = "";
1public static void main(String[] args) {
0Connection conn = null;
1Statement stmt = null;
1try{
1//STEP 2: Register JDBC driver
[Link]("[Link]");
1//STEP 3: Open a connection
[Link]("Connecting to database...");
1conn = [Link](DB_URL,"root","");
4//STEP 4: Execute a query
[Link]("Creating statement...");
5stmt = [Link]();
1String sql;
6sql = "SELECT id, first, last, age FROM Employees";
1ResultSet rs = [Link](sql);
//STEP 5: Extract data from result set
7
while([Link]()){
1
//Retrieve by column name
8int id = [Link]("id");
1int age = [Link]("age");
9String first = [Link]("first");
2String last = [Link]("last");
0//Display values
[Link]("ID: " + id);
[Link](", Age: " + age);
[Link](", First: " + first);
[Link](", Last: " + last);
2}
3//STEP 6: Clean-up environment
[Link]();
[Link]();
[Link]();
}catch(SQLException se){
5
//Handle errors for JDBC
[Link]();
6}catch(Exception e){
2//Handle errors for [Link]
[Link]();
2}finally{
8//finally block used to close resources
2try{
9if(stmt!=null)
[Link]()
0}catch(SQLException se2){
3}// nothing can be done
1try{
3if(conn!=null)
[Link]();
3}catch(SQLException se){
[Link]();
3
}//end finally try
3
}//end try
[Link]("Goodbye!");
3}//end main
5} // end Example
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
Above code creates a table in your localhost database. To insert the
values in the created database, you can refer to the below code. I will be
writing the code only for step 4. Rest of the code remains the same as
above.

1//STEP 4: Execute a query


[Link]("Creating table in given database...");
3stmt = [Link]();
4String sql = "CREATE TABLE EMPLOYEES " +
"(id INTEGER not NULL, " +
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1" first VARCHAR(255), " +
5" last VARCHAR(255), " +
1" age INTEGER, " +
6" PRIMARY KEY ( id ))";
[Link](sql);
[Link]("Created table in given database...");
[Link]("Inserting records into the table...");
stmt =[Link]();
8
String sql ="INSERT INTO Employees VALUES (100, 'Kriss', 'Kurian', 18)";
1
[Link](sql);
9sql = "INSERT INTO Employees VALUES (101, 'Enrique', 'John', 25)";
[Link](sql);
0sql= "INSERT INTO Employees (102, 'Taylor', 'Swift', 30)";
[Link](sql);
1sql= "INSERT INTO Employees VALUES(103, 'Linkin', 'Park', 28)";
[Link](sql);
[Link]("Inserted records into the table...");
So this is how you can establish a connection to the database and insert
values in the tables. Now let’s move further and understand various JDBC
Driver Types
Java Certification Training Course

 Instructor-led Sessions
 Real-life Case Studies
 Assignments
 Lifetime Access

Explore Curriculum

Get Certified With Industry Level Projects & Fast Track


Your Career Take A Look!
Advanced Java Tutorial: JDBC Driver Types
JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server. Essentially, a JDBC driver makes it
possible to do three things:
1. Establish a connection with a data source.
2. Send queries and update statements to the data source.
3. Process the results.
For example, the use of JDBC drivers enables you to open a database
connection to interact with it by sending SQL or database commands.

There are 4 types of drivers, namely:

Type 1: JDBC-ODBC Bridge Diver

In Type 1 driver, a JDBC bridge accesses ODBC drivers installed on each


client machine. Further, ODBC configures Data Source Name (DSN) that
represents the target database.
When Java first came
out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API
calls, which are unique to the database. These drivers are typically
provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The


JDBC clients use standard network sockets to communicate with a
middleware application server. The socket information is then translated
by the middleware application server into the call format required by the
DBMS and forwarded to the database server.

This
kind of driver is extremely flexible since it requires no code installed on
the client and a single driver can actually provide access to multiple
databases. You can think of the application server as a JDBC “proxy,”
meaning that it makes calls for the client application. As a result, you
need some knowledge of the application server’s configuration in order to
effectively use this driver type. Your application server might use a Type
1, 2, or 4 drivers to communicate with the database.

Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with


the vendor’s database through a socket connection. This is the highest
performance driver available for the database and is usually provided by
the vendor itself.
This
kind of driver is extremely flexible, you don’t have to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.

MySQL’s Connector/J driver is a Type 4 driver. Because of the proprietary


nature of their network protocols, database vendors usually supply type 4
drivers.

Subscribe to our youtube channel to get new updates..!

So here comes the question, which Driver should be used?

 If you are accessing one type of database, such as Oracle, Sybase,


or IBM, the preferred driver type is 4.
 If your Java application is accessing multiple types of databases at
the same time, type 3 is the preferred driver.
 Type 2 drivers are useful in situations, where a type 3 or type 4
driver is not available yet for your database.
 The type 1 driver is not considered a deployment-level driver and is
typically used for development and testing purposes only.

Now, let’s jump into the last topic of JDBC and understand various types of
connections.

Advanced Java Tutorial: JDBC Connections


 Import JDBC Packages: Add import statements to your Java
program to import required classes in your Java code.
 Register JDBC Driver: This step causes the JVM to load the desired
driver implementation into memory so that it can fulfill your JDBC
requests. There are 2 approaches to register a driver.
 The most common approach to register a driver is to use
Java’s forName()method to dynamically load the driver’s
class file into memory, which automatically registers it. This
method is preferable because it allows you to make the driver
registration configurable and portable. Refer the below code.

1try {
[Link]("[Link]");
3}
4catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
7}

 The second approach you can use to register a driver is to use


the static registerDriver()method.

1
try {
2
Driver myDriver = new [Link]();
3 [Link]( myDriver );
4 }
5catch(ClassNotFoundException ex)
6{
[Link]("Error: unable to load driver class!");
[Link](1);
9}
You should use the registerDriver() method if you are using a non-JDK
compliant JVM, such as the one provided by Microsoft.

 Database URL Formulation: This is to create a properly formatted


address that points to the database to which you wish to connect.
After you’ve loaded the driver, you can establish a connection using
the [Link]() method.
[Link]() methods are−
 getConnection(String url)
 getConnection(String url, Properties prop)
 getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address


that points to your database.

A table lists down the popular JDBC driver names and database URL.

RDBMS JDBC Driver Name URL


jdbc:mysql://hostname/
1. MYSQL [Link]
databaseName
jdbc:oracle:thin:@hostname:port
2. Oracle
[Link] Number:databaseName
jdbc:sybase:Tds:hostname: port
3. Sybase [Link]
Number/databaseName

 Create a connection object

You can simply create or open a connection using database url, username,
and password and also using properties object. A Properties object holds a
set of keyword-value pairs. It is used to pass the driver properties to the
driver during a call to the getConnection() method.

 Close

At the end of your JDBC program, we have to close all the database
connections to end each database session. However, if you forget, Java’s
garbage collector will close the connection when it cleans up stale objects.

[Link]();// Used to close the connection


That was all about Java Database Connectivity. If you wish to know more
about JDBC, you can refer these interview questions. Now move ahead
and learn Servlets.

Advanced Java Tutorial: Introduction to


Servlets
A servlet is a Java programming language class that is used to extend the
capabilities of servers that host applications accessed by means of a
request-response programming model. Although servlets can respond to
any type of request, they are commonly used to extend the applications
hosted by web servers.
Servlet can be described as follows:


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

o It 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 It is also a class that extends the capabilities of the servers
and responds to the incoming requests. It can respond to any
requests.

Advanced Java Tutorial: Servlet Life Cycle

The entire life cycle of a Servlet is managed by the Servlet


container which uses the [Link] interface to understand the
Servlet object and manage it.

Programming & Frameworks Training

FULL STACK WEB DEVELOPMENT INTERNSHIP PROGRAM


Full Stack Web Development Internship Program
Reviews
5(28101)

JAVA CERTIFICATION TRAINING COURSE


Java Certification Training Course
Reviews
4(72928)

FLUTTER APPLICATION DEVELOPMENT COURSE


Flutter Application Development Course
Reviews
5(11141)

PYTHON SCRIPTING CERTIFICATION TRAINING


Python Scripting Certification Training
Reviews
5(13473)

SPRING FRAMEWORK CERTIFICATION COURSE


Spring Framework Certification Course
Reviews
5(11272)

[Link] CERTIFICATION TRAINING COURSE


[Link] Certification Training Course
Reviews
5(9483)

ADVANCED JAVA CERTIFICATION TRAINING


Advanced Java Certification Training
Reviews
5(6452)

PHP & MYSQL WITH MVC FRAMEWORKS CERTIFICATION TRAINING


PHP & MySQL with MVC Frameworks Certification Training
Reviews
5(4633)

DATA STRUCTURES AND ALGORITHMS USING JAVA INTERNSHIP


PROGRAM
Data Structures and Algorithms using Java Internship Program
Reviews
5(30032)

Next
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes
through four stages,

 Loading a Servlet.
 Initializing the Servlet.
 Request handling
 Destroying the Servlet.
Let’s look
at each of these stages in details:

1. Loading a Servlet: The first stage of the Servlet life cycle involves
loading and initializing the Servlet by the Servlet container. The Web
container or Servlet Container can load the Servlet at either of the
following two stages :
o Initializing the context, on configuring the Servlet with a zero
or positive integer value.
o If the Servlet is not preceding the stage, it may delay the
loading process until the Web container determines that this
Servlet is needed to service a request.
2. Initializing a Servlet: After the Servlet is instantiated successfully,
the Servlet container initializes the instantiated Servlet object. The
container initializes the Servlet object by invoking
the init(ServletConfig) method which accepts ServletConfig object
reference as a parameter.
3. Handling request: After initialization, the Servlet instance is ready
to serve the client requests. The Servlet container performs the
following operations when the Servlet instance is located to service
a request :
o It creates the ServletRequest and ServletResponse. In this
case, if this is an HTTP request then the Web container
creates HttpServletRequest and HttpServletResponse obj
ects which are subtypes of
the ServletRequest and ServletResponse objects
respectively.
4. Destroying a Servlet: When a Servlet container decides to
destroy the Servlet, it performs the following operations,
o It allows all the threads currently running in the service
method of the Servlet instance to complete their jobs and get
released.
o After currently running threads have completed their jobs, the
Servlet container calls the destroy() method on the Servlet
instance.

After the destroy() method is executed, the Servlet container releases all
the references of this Servlet instance so that it becomes eligible for
garbage collection.

Now that you have understood the basics of a servlet, let’s move further
and understand what are the steps involved to create a Servlet
application.

Advanced Java Tutorial: Steps to create


Servlet
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Add mappings to [Link] file
5. Start the server and deploy the project
6. Access the servlet

Now, based on the above steps let’s write a program and understand how
servlet works.

Step 1: To run a servlet program, we should have Apache tomcat server


installed and configured. Once the server is configured, you can start with
your program.

Step 2: For a servlet program, you need 3 files – [Link] file,


Java class file, and [Link] file. The very first step is to create Dynamic
Web Project and then proceed further

Step 3: Now let’s see how to add 2 numbers using servlets and display
the output in the browser.

First, I will write [Link] file

1<!DOCTYPE html>
2<html>
<body>
3
4
5
6
7
8
9
1
0<form action ="add">
1 Enter 1st number: <input type="text" name="num1">
1 Enter 2nd number: <input type="text" name="num2">
1<input type ="submit">
2</form>
1
3
1</body>
4</html>
Above program creates a form to enter the numbers for the addition
operation.

Step 4: Now without the Java class file, you can’t perform addition on 2
numbers. So let’s write a class file.

1
2
3
4
5
6
7
8import [Link];
9import [Link];
1import [Link];
0import [Link];
1import [Link];
public class Add extends HttpServlet{
1
public void service(HttpServletRequest req, HttpServletResponse res) throws IO
1
{
2 int i = [Link]([Link]("num1"));
1 int j = [Link]([Link]("num2");
3 int k= i+j;
1 PrintWriter out = [Link]();
4 [Link]("Result is"+k);
1 }
5}
Step 5: After writing the Java class file, the last step is to add mappings
to the [Link] file. Let’s see how to do that.
Step 6: [Link] file will be present in the WEB-INF folder of your web
content. If it is not present, then you can click on Deployment Descriptor
and click on Generate Deployment Descriptor Stub.

Step 7: After that, you can proceed further and add the mappings to it.

1
2
3
4
5<?xml version="1.0" encoding="UTF-8"?>
6<web-app xmlns:xsi="<a href="[Link]
7href="[Link] xsi:s
8href="[Link] <a hre
9app_3_0.xsd">[Link] version=<em>
1 <display-name>Basic</display-name>
0 <servlet>
1 <servlet-name>Addition</servlet-name>
<servlet-class>[Link]</servlet-class>
1
</servlet>
1
<servlet-mapping>
2 <servlet-name>Addition</servlet-name>
1 <url-pattern>/add</url-pattern>
3</servlet-mapping>
1<welcome-file-list>
4 <welcome-file>[Link]</welcome-file>
1 </welcome-file-list>
5</web-app>
Step 8: After all this, you can run the program by starting the server. You
will get the desired output on the browser.

Basically, this is how servlet should be configured. Now let’s move further
and understand the concept of session tracking.

Session Tracking
Session simply means a particular interval of time. And session
tracking is a way to maintain state (data) of a user. It is also known
as session management in servlet. We know that the Http protocol is
stateless, so we need to maintain state using session tracking techniques.
Each time user requests to the server, the server treats the request as the
new request. So we need to maintain the state of a user to recognize a
particular user.
You can see in the figure when you send a request it is considered as a
new request.

In order to recognize the particular user, we need session tracking. So this


was all about Servlets.

Now, let’s dive into the last section of our blog and understand what is
JSP.

Advanced Java Tutorial: Java Server Pages


JSP or Java Server Pages is a technology that is used to create web
application just like Servlet technology. It is an extension to Servlet – as it
provides more functionality than servlet such as expression language,
JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages
are easier to maintain than Servlet because we can separate designing
and development. It provides some additional features such as Expression
Language, Custom Tags, etc.

Now let’s see various features of JSP with the help of below figure.
 Portable: JSP tags will process and execute by the server side web
container, So that these are browser independent and J2EE server
independent.
 Powerful: JSP consists of bytecode so that all Java features are
applicable in case of JSP like robust, dynamic, secure, platform
independent.
 Flexible: It allows to define custom tags so that the developer can
fill conferrable to use any kind, framework based markup tags in
JSP.
 Fast Development: If JSP page is modified, we don’t need to
recompile and redeploy the project. The Servlet code needs to be
updated and recompiled if we have to change the look and feel of
the application.
 Tracking the User: JSP allows us to track the selections made by
the user during user interaction with the website by maintaining the
information in the session or cookies
 Easy: JSP is easy to learn, easy to understand and easy to develop.
JSPs are more convenient to write than Servlets because they allow
you to embed Java code directly into your HTML pages.

Now that you understood what is JSP, let’s see how JSP and Servlets differ
from each other and why JSP is better than Servlets with the help of below
table.

Java Certification Training Course

Weekday / Weekend BatchesSee Batch Details

JSP Servlets
Extension to Servlet Not an extension to servlet
Easy to Maintain Bit complicated
No need to recompile or The code needs to be
redeploy recompiled
Less code than a servlet More code compared to JSP
Now let’s dig deeper into Java Server Pages and understand Life Cycle of
JSP.

Advanced Java Tutorial: Life Cycle of JSP


The JSP pages follow these phases:

1. Translation of JSP Page


2. Compilation of JSP Page
3. Classloading (the classloader loads class file)
4. Instantiation (Object of the Generated Servlet is created)
5. Initialization ( the container invokes jspInit())
6. Request processing ( the container invokes _jspService())
7. Destroy ( the container invokes jspDestroy())

As depicted in the above diagram, a JSP page is translated into Servlet by


the help of JSP translator. And then, JSP translator is a part of the web
server which is responsible for translating the JSP page into Servlet. After
that, Servlet page is compiled by the compiler and gets converted into the
class file. Moreover, all the processes that happen in Servlet are
performed on JSP later, like initialization, committing response to the
browser and destroy.

Advanced Java Tutorial: JSP Scripting


Elements:
The scripting elements provide the ability to insert java code inside the
JSP. There are three types of scripting elements:

 scriptlet tag – A scriptlet tag is used to execute Java source code


in JSP.
Syntax is: <% java source code %>
 expression tag – The code placed within JSP expression
tag is written to the output stream of the response. So you need not
write [Link]() to write data. It is mainly used to print the values
of variable or method.
Syntax : <%= statement %>
 declaration tag – The JSP declaration tag is used to declare fields
and methods. The code written inside the JSP declaration tag is
placed outside the service() method of an auto-generated servlet.
So it doesn’t get memory at each request.
Syntax: <%! field or method declaration %>

You might also like