Unit3 JDBC
Unit3 JDBC
JDBC OVERVIEW
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database, and processing the results. 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
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
o Clob class
o Types class
Why Should We Use JDBC?
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But ODBC API uses ODBC driver that 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.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
Advantage:
No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
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:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
Register the Driver
Create connection
Create statement
Execute queries
Close connection
1)Register the driver
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className) throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
public static Connection getConnection(String url,String name,String password)
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","syst
em","password");
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.
3)Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
2)Prepared Statement
The PreparedStatement interface extends the Statement interface. It represents a
precompiled SQL statement which can be executed multiple times. This accepts
parameterized SQL queries and you can pass 0 or more parameters to this query.
Initially, this statement uses place holders “?” instead of parameters, later on, you can pass
arguments to these dynamically using the setXXX() methods of
the PreparedStatement interface.
Creating a PreparedStatement:
You can create an object of the PreparedStatement (interface) using
the prepareStatement() method of the Connection interface. This method accepts a query
(parameterized) and returns a PreparedStatement object.
When you invoke this method the Connection object sends the given query to the database to
compile and save it. If the query got compiled successfully then only it returns the object.
To compile a query, the database doesn’t require any values so, you can use (zero or
more) placeholders (Question marks “?”) in the place of values in the query.
For example, if you have a table named Employee in the database created using the
following query:
CREATE TABLE Employee(Name VARCHAR(255), Salary INT NOT NULL, Location
VARCHAR(255));
Then, you can use a PreparedStatement to insert values into it as shown below.
//Creating a Prepared Statement
String query="INSERT INTO Employee(Name, Salary, Location)VALUES(?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
Setting values to the place holders
The PreparedStatement interface provides several setter methods such as setInt(), setFloat(),
setArray(), setDate(), setDouble() etc.. to set values to the place holders of the prepared
statement.
These methods accepts two arguments one is an integer value representing the placement
index of the place holder and the other is an int or, String or, float etc… representing the
value you need to insert at that particular position.
Once you have created a prepared statement object (with place holders) you can set values to
the place holders of the prepared statement using the setter methods as shown below:
pstmt.setString(1, "Amit");
pstmt.setInt(2, 3000);
pstmt.setString(3, "Hyderabad");
Executing the Prepared Statement
Once you have created the PreparedStatement object you can execute it using one of the
execute() methods of the PreparedStatement interface namely, execute(), executeUpdate()
and, executeQuery().
execute(): This method executes normal static SQL statements in the current prepared
statement object and returns a boolean value.
executeQuery(): This method executes the current prepared statement and returns
a ResultSet object.
executeUpdate(): This method executes SQL DML statements such as insert update
or delete in the current Prepared statement. It returns an integer value representing the
number of rows affected.
Example program to demonstrate PreparedStatement:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
3)CallableStatement
The CallableStatement interface provides methods to execute stored procedures. Since the
JDBC API provides a stored procedure SQL escape syntax, you can call stored procedures of
all RDBMS in a single standard way.
Creating a CallableStatement
You can create an object of the CallableStatement (interface) using
the prepareCall() method of the Connection interface.
This method accepts a string variable representing a query to call the stored procedure and
returns a CallableStatement object.
A CallableStatement can have input parameters or, output parameters or, both. To pass input
parameters to the procedure call you can use place holder and set values to these using the
setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface.
Suppose, you have a procedure name myProcedure in the database you can prepare a callable
statement as:
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
Setting values to the input parameters
You can set values to the input parameters of the procedure call using the setter methods.
These accept two arguments one is an integer value representing the placement index of the
input parameter and the other is an int or, String or, float etc… representing the value you
need to pass an input parameter to the procedure.
Note: Instead of index you can also pass the name of the parameter in String format.
cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
Executing the Callable Statement:
Once you have created the CallableStatement object you can execute it using one of
the execute() method.
cstmt.execute();
Example program to demonstrate CallableStatement:
Let's create the simple function in the database first.
create or replace function sum4 (n1 in number,n2 in number)
return number
is
temp number(8);
begin
temp :=n1+n2;
return temp;
end;
/
Now, let's write the simple program to call the function.
import java.sql.*;
public class FuncSum {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();
System.out.println(stmt.getInt(1));
}
}
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing
devices.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes
Java Networking Terminology
The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Add
5. ress
6. Connection-oriented and connection-less protocol
7. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
java.net package
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces
i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to
the resource pointed by URLs.
The java.net package provides many classes to deal with networking applications in Java. A
list of these classes is given below:
o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler
List of interfaces available in java.net package:
o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily
Java InetAddress class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.google.com, www.facebook.com,
etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of
InetAddress represents the IP address with its corresponding host name. There are two types
of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface whereas
Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host
name resolutions.
IP Address
o An IP address helps to identify a specific resource on the network using a numerical
representation.
o Most networks combine IP with TCP (Transmission Control Protocol). It builds a
virtual bridge among the destination and the source.
There are two versions of IP address:
1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in
the ARAPNET in 1983. It is a widely used IP version to differentiate devices on network
using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses that is
more than 4 million addresses.
Features of IPv4:
o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with the class
based addressing scheme.
o It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet
addresses. It provides solutions for the problems present in IPv4. It provides 128-bit address
space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also
identified with a name IPng (Internet Protocol next generation).
Features of IPv6:
o It has a stateful and stateless both configurations.
o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.
TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a network via
internet.
o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data
packets over the internet.
o The two main protocols used in this communication model are:
o TCP i.e. Transmission Control Protocol. TCP provides the way to create a
communication channel across the network. It also helps in transmission of
packets at sender end as well as receiver end.
o IP i.e. Internet Protocol. IP provides the address to the nodes connected on the
internet. It uses a gateway computer to check whether the IP address is correct
and the message is forwarded correctly or not.
Java InetAddress Class Methods
Method Description
public static InetAddress getByName(String host) It returns the instance of InetAddress containing
throws UnknownHostException LocalHost IP and name.
public static InetAddress getLocalHost() throws It returns the instance of InetAdddress containing
UnknownHostException local host name and address.
Method Description
public boolean equals(Object obj) it compares the URL with the given object.
JavaBean
A JavaBean is a Java class that should follow the following conventions:
o It should have a no-arg constructor.
o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as getter
and setter methods.
Why use JavaBean?
Java Bean is a reusable software component. A bean encapsulates many objects into one
object so that we can access this object from multiple places. Moreover, it provides easy
maintenance.
Simple example of JavaBean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to
read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to
write that property. This method is called the mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:
o The JavaBean properties and methods can be exposed to another application.
o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
o JavaBeans are mutable. So, it can't take advantages of immutable objects.
o Creating the setter and getter method for each property separately may lead to the
boilerplate code.
Java RMI
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing
in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between
Java programs. It is provided in the package java.rmi.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the server) and a
client program (resides on the client).
• Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
• The client program requests the remote objects on the server and tries to invoke its methods.
The following diagram shows the architecture of an RMI application.
Let us now discuss the components of this architecture.
• Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
• Stub − A stub is a representation (proxy) of the remote object at client. It resides in the
client system; it acts as a gateway for the client program.
• Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
• RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.
Working of an RMI Application
The following points summarize how an RMI application works –
• When the client makes a call to the remote object, it is received by the stub which
eventually
passes this request to the RRL.
• When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.
• The RRL on the server side passes the request to the Skeleton (proxy on the server) which
finally invokes the required object on the server.
• The result is passed all the way back to the client.
Marshalling and Unmarshalling
Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These parameters
may be of primitive type or objects. In case of primitive type, the parameters are put together
and a header is attached to it. In case the parameters are objects, then they are serialized. This
process is known as marshalling.
At the server side, the packed parameters are unbundled and then the required method is
invoked. This process is known as unmarshalling.
RMI Registry
RMI registry is a namespace on which all server objects are placed. Each time the server
creates an object, it registers this object with the RMIregistry (using bind() or reBind()
methods). These are registered using a unique name known as bind name. To invoke a remote
object, the client needs a reference of that object. At that time, the client fetches the object
from the registry using its bind name (using lookup() method).
The following illustration explains the entire process
Goals of RMI
• To minimize the complexity of the application.
• To preserve type safety.
• Distributed garbage collection.
• Minimize the difference between working with local and remote objects.