Professional Documents
Culture Documents
Unit - Ii: Java - SQL
Unit - Ii: Java - SQL
Unit - Ii: Java - SQL
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
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 database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
1
o Clob class
o Types class
What is 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)
2
In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
3
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
4
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Method Description
5
1) public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.
2) public static void deregisterDriver(Driver is used to deregister the given driver (drop
driver): the driver from the list) with
DriverManager.
This package provides the APIs for accessing and processing data which is stored in the
database especially relational database by using the java programming language. It
includes a framework where we different drivers can be installed dynamically to access
different databases especially relational databases.
This java.sql package contains API for the following :
1. Making a connection with a database with the help of DriverManager class
6
statements from the Statement object.
c). CallableStatement interface : This interface is used to call database stored procedures.
d). Connection interface : It provides methods for creating statements and managing their
connections and properties.
e). Savepoint : It helps to make the savepoints in a transaction.
a). ResultSet interface: This object maintains a cursor pointing to its current row of data.
The cursor is initially positioned before the first row. The next method of the resultset
interface moves the cursor to the next row and it will return false if there are no more rows
in the ResultSet object. By default ResultSet object is not updatable and has a cursor that
moves forward only.
4.) Providing Standard mappings for SQL types to classes and interfaces in Java
Programming language.
7
c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch
update are not executed successfully.
d). DataTruncation: It is thrown to indicate that the data may have been truncated.
7). Custom mapping an SQL user- defined type (UDT) to a class in the java
programming language.
a). SQLData interface: It gives the mapping of a UDT to an intance of this class.
b). SQLInput interface: It gives the methods for reading UDT attributes from a stream.
c). SQLOutput: It gives the methods for writing UDT attributes back to a stream.
8
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the
classpath, and then JDBC driver manager can detect and load the driver automatically.
9
2. while(rs.next()){
3. System.out.println(rs.getInt(1)+" "+rs.getString(2));
4. }
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCU
R_UPDATABLE);
is used to move the cursor to the one row previous from the
2) public boolean previous():
current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
10
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int is used to move the cursor to the specified row number in the
row): ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row number in the
row): ResultSet object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the current
columnIndex): row as int.
8) public int getInt(String is used to return the data of specified column name of the current
columnName): row as int.
9) public String getString(int is used to return the data of specified column index of the current
columnIndex): row as String.
10) public String getString(String is used to return the data of specified column name of the current
columnName): row as String.
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
11
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the
server name on which mysql is running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in such case, we need to replace
the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
12
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
Two ways to load the jar file:
1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath
) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
temporary
permanent
13
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the
driver, localhost is the server name on which oracle is running, we may also use IP address,
1521 is the port number and XE is the Oracle service name. You may get all these information
from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query
to create a table.
14
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
temporary
permanent
15
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
16
executes the select query. It returns an instance of
public ResultSet executeQuery()
ResultSet.
JDBC Exception
The Exception are the set of condition that occurred when an abnormal condition try to interrupt
the normal flow of the code during the execution of program. Exception Occurred in JDBC
Connectivity when a connection object do not find a suitable driver to connect a url-database.
Understand with Example
The Tutorial illustrates an example from JDBC Exception. In this Tutorial we want to describe
you a code that show an exception in JDBC.For this we have a class JdbcException. The first
step is to import a package name java.sql include a definition for all the classes that provides you
17
network interface to communicate between front end and back end application. The next is to
load the driver by calling class. for name( ) with driver class passed as argument.
Driver.getConnection ( ) : This is used to built connection between url and database. In case
there is an exception in try block, the subsequent catch block caught and handle the exception,
The exception show you no suitable driver is found.
con.create Statement ( ) : This is used to create a Sql object. An sql object is used to send and
execute the query in backend database.
executeQuery ( ): This is used to return the result set obtained from the record set of the
database. The select statement is used to retrieve the result set from the database.
In this program code, the exception occurred in try block, therefore the subsequent catch block
show the exception that a suitable driver do not found using print ln.Once the suitable driver is
found the print ln print and display the element of no,name,id and dob.
rs.getString ( ) -The Result set object call a get String ( ),returns you a record set into a
formatted string element.
JdbcExceptions.java
import java.sql.*;
Class.forName(driver);
try {
con = DriverManager.getConnection(url + db, user, pass);
} catch (Exception e) {
System.err.println(e);
url = "jdbc:mysql://localhost:3306/";
db = "komal";
18
user = "root";
pass = "root";
JSP Tutorial
Java Server Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications. JSP have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will
teach you how to use Java Server Pages to develop your web applications in simple and easy steps.
This tutorial has been prepared for the beginners to help them understand basic functionality of
Java Server Pages (JSP) to develop your web applications. After completing this tutorial you will find
yourself at a moderate level of expertise in using JSP from where you can take yourself to next
levels.
19
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3
Create the Employee table in the TEST database as follows − −
mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>
20
mysql>
SELECT Operation
Following example shows how we can execute the SQL SELECT statement using JTSL in JSP
programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
21
</tr>
</c:forEach>
</table>
</body>
</html>
Access the above JSP, the following result will be displayed −
22
Introduction to Struts framework
Model-1 Architecture
In this Architecture all kinds of requirements get fulfilled in one layer. The user provides
request to the jsp and jsp provides response to the user. This Architecture uses a set of
jsp to implement presentation logic, business logic, controlling logic. It is suitable for
small scale requirement due to its simplicity. It does not provide reusability.
Model-2 Architecture
1. Model
2. Controller
3. View
Model: - This layer implements business logic and contains data. State of users can be
stored in this layer. This layer can be created by using a set of java beans.
Controller: - This layer implements controlling logic. It takes decision to make visible
appropriate view to the appropriate users. This layer can be created by using a servlet
and a set of helper classes. The users gives request to the servlet present in the layer.
View: - This layer implements presentation logic of the application. It provides response
to the user. A set of Jsp can be used to create this layer.
Introduction to Struts
Model: - This layer implements business logic and contains data. This can be created by
using a set of java beans called as form bean. Struts provide a predefined class as the
super class of all form beans.
Controller: - This layer implements controlling logic of the application. It takes decision
to make visible appropriate view to appropriate users. This can be created by using a
controlling servlet and a set of helper class called as form- action. Struts provide a
predefined servlet as the controlling servlet .The controlling servlet receives request from
the users. Struts provide a predefined class as the super class of all form action classes.
23
View: - This layer implements presentation logic. It provides response to the users. This
layer can be created by using a set of Jsp. Struts provides tag libraries for this layer.
Installation of struts
Configuration of struts
Create a configuration file named as struts-config.xml inside WEB-INF folder. This file
contains information about form-bean, form-action, and forwards.
Tips: -
<servlet>
<servlet-name>x</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>x</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Requirements
24
3. Create a form-action to validate input of user and to provide appropriate forwards
names to controlling servlets.
4. Provide information in struts-config.xml.
5. Create page for each forwards.
1. Create a class in the same package where form-bean exists and this class must
inherit org.apache.struts.action.Action class.
2. Override execute () method to implement validation logic and to return a
forward.Return type of this method must be org.apache.struts.ActionForward.This
method accept four parameters as follows below.
Compile formbean and action file simultaneously by using servlet-api.jar and struts-core-
1.3.8.jar in classpath.The jar file of struts(struts-core-1.3.8.jar) can be found in lib folder
of the context,after installation of structs.
Here logs is the package folder where we stored both the form bean and fom action files.
<form-beans>
<form-bean name="name to map formbean with form action" type="class name with
25
package name of the form bean" />
</form-beans>
2. Supply information about form-action and forwards by using the following tags in
struts-config.xml file
<action-mappings>
<action name="mapping name specified in formbean" path="value of action attribute
present in from" type="class name of form action" >
<forward name="name of forward used by form action" path="name of the page to be
visible" />
<forward name=" name of forward used by form action " path=" name of the page to be
visible " />
</action>
</action-mappings>
26