0% found this document useful (0 votes)
46 views

Unit-2 Networking & JDBC

The document provides an introduction to Java networking concepts including sockets, IP addresses, protocols, and port numbers. It discusses how Java supports TCP and UDP and describes connection-oriented and connection-less protocols. Examples are given of Java socket programming using the Socket and ServerSocket classes to establish communication between a client and server.

Uploaded by

Sai Harsha2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Unit-2 Networking & JDBC

The document provides an introduction to Java networking concepts including sockets, IP addresses, protocols, and port numbers. It discusses how Java supports TCP and UDP and describes connection-oriented and connection-less protocols. Examples are given of Java socket programming using the Socket and ServerSocket classes to establish communication between a client and server.

Uploaded by

Sai Harsha2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to 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 Address
5. Connection-oriented and connection-less protocol
6. 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.

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 Socket Programming
Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

Here, we are going to make one-way client and server communication. In this application, client sends a message to
the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The
Socket class is used to communicate client and server. Through this class, we can read and write message. The
ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client
is connected. After the successful connection of client, it returns the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a
socket.

Important methods

Method Description

1) public InputStream getInputStream() returns the InputStream attached with this


socket.

2)public OutputStream getOutputStream() returns the OutputStream attached with this


socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the
clients.

Important methods

Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2) public synchronized void closes the server socket.


close()

Example of Java Socket Programming


Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port
number for the communication between the client and server. You may also choose any other port number. The
accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.

1. ServerSocket ss=new ServerSocket(6666);


2. Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address
or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same
system.

1. Socket s=new Socket("localhost",6666);

Let's see a simple of Java socket programming where client sends a text and server receives and prints it.

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

File: MyClient.java

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute each program at each command prompt as
displayed in the below figure.

After running the client application, a message will be displayed on the server console.

ADVERTISEMENT BY ADRECOVER

Example of Java Socket Programming (Read-Write both side)


In this example, client will write first to the server then server will receive and print the text. Then server will write to
the client and client will receive and print the text. The step goes on.

File: MyServer.java

import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}

File: MyClient.java

import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}}

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the
World Wide Web. For example:

1. https://www.javatpoint.com/java-tutorial

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the
port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.

Constructors of Java URL class


URL(String spec)

Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)

Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)

Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)

Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)

Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)

Creates an instance of a URL by parsing the given spec with the specified handler within a given context.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of URL class are given below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

public String toString() it returns the string representation of the URL.

public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.

public URLConnection it returns the instance of URLConnection i.e. associated


openConnection() with this URL.

public boolean equals(Object obj) it compares the URL with the given object.

public Object getContent() it returns the content of the URL.

public String getRef() it returns the anchor or reference of the URL.

public URI toURI() it returns a URI of the URL.

Example of Java URL class


//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

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

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

URLConnection Class

The Java URLConnection class represents a communication link between the URL and
the application. It can be used to read and write data to the specified resource referred
by the URL.

What is the URL?

o URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that
helps to find a resource on the World Wide Web (WWW).
o URL has two components:

1. The protocol required to access the resource.


2. The location of the resource.

Features of URLConnection class

1. URLConnection is an abstract class. The two subclasses HttpURLConnection and


JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any
resource referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we
can use it to read or write or get further information like content length, etc.

Constructors

Constructor Description

1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.

URLConnection Class Methods

Method Description

void addRequestProperty(String key, String value) It adds a general request property specified
by a key-value pair

void connect() It opens a communications link to the


resource referenced by this URL, if such a
connection has not already been
established.

boolean getAllowUserInteraction() It returns the value of the


allowUserInteraction field for the object.

int getConnectionTimeout() It returns setting for connect timeout.

Object getContent() It retrieves the contents of the URL


connection.

Object getContent(Class[] classes) It retrieves the contents of the URL


connection.

String getContentEncoding() It returns the value of the content-


encoding header field.

int getContentLength() It returns the value of the content-length


header field.

long getContentLengthLong() It returns the value of the content-length


header field as long.

String getContentType() It returns the value of the date header field.

long getDate() It returns the value of the date header field.

static boolean getDefaultAllowUserInteraction() It returns the default value of the


allowUserInteraction field.

boolean getDefaultUseCaches() It returns the default value of an


URLConnetion's useCaches flag.

boolean getDoInput() It returns the value of the URLConnection's


doInput flag.

boolean getDoInput() It returns the value of the URLConnection's


doOutput flag.

long getExpiration() It returns the value of the expires header


files.

static FileNameMap getFilenameMap() It loads the filename map from a data file.
String getHeaderField(int n) It returns the value of nth header field

String getHeaderField(String name) It returns the value of the named header


field.

long getHeaderFieldDate(String name, long Default) It returns the value of the named field
parsed as a number.

int getHeaderFieldInt(String name, int Default) It returns the value of the named field
parsed as a number.

String getHeaderFieldKey(int n) It returns the key for the nth header field.

long getHeaderFieldLong(String name, long Default) It returns the value of the named field
parsed as a number.

Map<String, List<String>> getHeaderFields() It returns the unmodifiable Map of the


header field.

long getIfModifiedSince() It returns the value of the object's


ifModifiedSince field.

InputStream getInputStream() It returns an input stream that reads from


the open condition.

long getLastModified() It returns the value of the last-modified


header field.

OutputStream getOutputStream() It returns an output stream that writes to


the connection.

Permission getPermission() It returns a permission object representing


the permission necessary to make the
connection represented by the object.

int getReadTimeout() It returns setting for read timeout.

Map<String, List<String>> getRequestProperties() It returns the value of the named general


request property for the connection.

URL getURL() It returns the value of the URLConnection's


URL field.

boolean getUseCaches() It returns the value of the URLConnection's


useCaches field.

Static String guessContentTypeFromName(String It tries to determine the content type of an


fname) object, based on the
specified file component of a URL.

static String It tries to determine the type of an input


guessContentTypeFromStream(InputStream is) stream based on the characters at the
beginning of the input stream.

void setAllowUserInteraction(boolean It sets the value of the allowUserInteraction


allowuserinteraction) field of this URLConnection.

static void It sets the ContentHandlerFactory of an


setContentHandlerFactory(ContentHandlerFactory fac) application.

static void setDefaultAllowUserInteraction(boolean It sets the default value of the


defaultallowuserinteraction) allowUserInteraction field for all future
URLConnection objects to the specified
value.

void steDafaultUseCaches(boolean defaultusecaches) It sets the default value of the useCaches


field to the specified value.

void setDoInput(boolean doinput) It sets the value of the doInput field for this
URLConnection to the specified value.

void setDoOutput(boolean dooutput) It sets the value of the doOutput field for
the URLConnection to the specified value.

How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection
class.

Syntax:

1. public URLConnection openConnection()throws IOException{}

Displaying Source Code of a Webpage by


URLConnecton Class
The URLConnection class provides many methods. We can display all the data of a
webpage by using the getInputStream() method. It returns all the data of the specified
URL in the stream that can be read and displayed.

Example of Java URLConnection Class

import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.vvitguntur.com/");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

InetAddress class
InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host
name for example www.javatpoint.com, 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.

InetAddress Class Methods


Method Description

public static InetAddress getByName(String host) It returns the instance of InetAddress


throws UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() throws It returns the instance of InetAdddress


UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

Example
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP
instead of TCP.

Datagram
Datagrams are collection of information sent from one device to another device via the established network. When
the datagram is sent to the targeted device, there is no assurance that it will reach to the target device safely and
completely. It may get damaged or lost in between. Likewise, the receiving device also never know if the datagram
received is damaged or not. The UDP protocol is used to implement the datagrams in Java.

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. It is a
mechanism used for transmitting datagram packets over network.`

A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class


o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port
Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given
Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and
binds it with the specified port number and host address.

Java DatagramSocket Class


Method Description

void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.

void close() It closes the datagram socket.

void connect(InetAddress It connects the socket to a remote address for the socket.
address, int port)

void disconnect() It disconnects the socket.

boolean getBroadcast() It tests if SO_BROADCAST is enabled.

DatagramChannel getChannel() It returns the unique DatagramChannel object associated


with the datagram socket.

InetAddress getInetAddress() It returns the address to where the socket is connected.

InetAddress getLocalAddress() It gets the local address to which the socket is connected.

int getLocalPort() It returns the port number on the local host to which the
socket is bound.

SocketAddress It returns the address of the endpoint the socket is bound


getLocalSocketAddress() to.

int getPort() It returns the port number to which the socket is connected.

int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this
DatagramSocket that is the buffer size used by the platform
for input on the DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.

boolean isConnected() It returns the connection state of the socket.

void send(DatagramPacket p) It sends the datagram packet from the socket.

void receive(DatagramPacket p) It receives the datagram packet from the socket.

Java DatagramPacket Class


Java DatagramPacket is a message that can be sent or received. It is a data container. If you send multiple packet, it
may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class


o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive
the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet.
This constructor is used to send the packets.

DatagramPacket Class Methods


Method Description

1) InetAddress getAddress() It returns the IP address of the machine to which the


datagram is being sent or from which the datagram
was received.

2) byte[] getData() It returns the data buffer.


3) int getLength() It returns the length of the data to be sent or the
length of the data received.

4) int getOffset() It returns the offset of the data to be sent or the offset
of the data received.

5) int getPort() It returns the port number on the remote host to


which the datagram is being sent or from which the
datagram was received.

6) SocketAddress getSocketAddress() It gets the SocketAddress (IP address + port number)


of the remote host that the packet is being sent to or
is coming from.

7) void setAddress(InetAddress iaddr) It sets the IP address of the machine to which the
datagram is being sent.

8) void setData(byte[] buff) It sets the data buffer for the packet.

9) void setLength(int length) It sets the length of the packet.

10) void setPort(int iport) It sets the port number on the remote host to which
the datagram is being sent.

11) void It sets the SocketAddress (IP address + port number)


setSocketAddress(SocketAddress of the remote host to which the datagram is being
addr) sent.

Example of Sending DatagramPacket by DatagramSocket

//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}

Output:

Example of Receiving DatagramPacket by DatagramSocket

//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

Output:
JDBC
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 have discussed the above four drivers in the next chapter.

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

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)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of
thin driver.

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.

ADVERTISEMENT BY ADRECOVER

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.

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.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.

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.


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.


Database Connectivity Steps

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class

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

1. public static void forName(String className)throws ClassNotFoundException

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the classpath, and t hen
JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

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

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

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

1. public Statement createStatement()throws SQLException

Example to create the statement object

1. Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException

Example to close connection

1. con.close();

Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close resources of type
Connection, ResultSet, and Statement.

It avoids explicit connection closing step.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

DriverManager class

The DriverManager class is the component of JDBC API and also a member of the java.sql package. The
DriverManager class acts as an interface between users and drivers. It keeps track of the drivers that are available and
handles establishing a connection between a database and the appropriate driver. It contains all the appropriate
methods to register and deregister the database driver class and to create a connection between a Java application
and the database. The DriverManager class maintains a list of Driver classes that have registered themselves by calling
the method DriverManager.registerDriver(). Note that before interacting with a Database, it is a mandatory process to
register the driver; otherwise, an exception is thrown.
Methods of the DriverManager Class
Method Description

1)public static synchronized is used to register the given driver with DriverManager.
void registerDriver(Driver No action is performed by the method when the given
driver) driver is already registered.

2)public static synchronized is used to deregister the given driver (drop the driver
void deregisterDriver(Driver from the list) with DriverManager. If the given driver has
driver) been removed from the list, then no action is performed
by the method.

3) public static Connection is used to establish the connection with the specified url.
getConnection(String url) The SQLException is thrown when the corresponding
throws SQLException Driver class of the given database is not registered with
the DriverManager.

4) public static Connection is used to establish the connection with the specified url,
getConnection(String url,String username, and password. The SQLException is thrown
userName,String password) when the corresponding Driver class of the given
throws SQLException database is not registered with the DriverManager.

5) public static Driver Those drivers that understand the mentioned URL
getDriver(String url) (present in the parameter of the method) are returned by
this method provided those drivers are mentioned in the
list of registered drivers.

6) pubic static int The duration of time a driver is allowed to wait in order to
getLoginTimeout() establish a connection with the database is returned by
this method.

7) pubic static void The method provides the time in seconds. sec mentioned
setLoginTimeout(int sec) in the parameter is the maximum time that a driver is
allowed to wait in order to establish a connection with the
database. If 0 is passed in the parameter of this method,
the driver will have to wait infinitely while trying to
establish the connection with the database.

8) public static Connection A connection object is returned by this method after


getConnection(String URL, creating a connection to the database present at the
Properties prop) throws mentioned URL, which is the first parameter of this
method. The second parameter, which is "prop", fetches
SQLException the authentication details of the database (username and
password.). Similar to the other variation of the
getConnection() method, this method also throws the
SQLException, when the corresponding Driver class of the
given database is not registered with the DriverManager.

Connection interface
A Connection is a session between a Java application and a database. It helps to establish a connection with the
database.

The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData, i.e., an object of
Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide
many methods for transaction management like commit(), rollback(), setAutoCommit(), setTransactionIsolation(), etc.

Commonly used methods of Connection interface:

1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.

2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object


that will generate ResultSet objects with the given type and concurrency.

3) public void setAutoCommit(boolean status): is used to set the commit status. By default, it is true.

4) public void commit(): saves the changes made since the previous commit/rollback is permanent.

5) public void rollback(): Drops all changes made since the previous commit/rollback.

6) public void close(): closes the connection and Releases a JDBC resources immediately.

Statement interface

The Statement interface provides methods to execute queries with the database. The statement interface is a factory
of ResultSet i.e. it provides factory method to get the object of ResultSet.

Commonly used methods of Statement interface:

The important methods of Statement interface are as follows:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.

Example of Statement interface

Let’s see the simple example of Statement interface to insert, update and delete the record.

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","system","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}

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,


2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from the
current position.

2) public boolean previous(): is used to move the cursor to the one row previous from
the current position.
3) public boolean first(): is used to move the cursor to the first row in result set
object.

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
row): the ResultSet object.

6) public boolean relative(int is used to move the cursor to the relative row number in
row): the 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
columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.

9) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.

10) public String is used to return the data of specified column name of the
getString(String columnName): current row as String.
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.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)

public void setString(int paramIndex, sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)

public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

1. create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

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","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Example of PreparedStatement interface that updates the record

PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");


stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
Example of PreparedStatement interface that deletes the record

PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");


stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");

Example of PreparedStatement interface that retrieve the records


of a table

PreparedStatement stmt=con.prepareStatement("select * from emp");


ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

ResultSetMetaData Interface
metadata means data about data i.e. we can get further information from the data.

If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface


Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in


the ResultSet object.

public String getColumnName(int index)throws it returns the column name of the


SQLException specified column index.

public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.

public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.


Syntax:

public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :

import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as database product name,
database product version, driver name, name of total number of tables, name of total number of views etc.

Commonly used methods of DatabaseMetaData interface


o public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the username of the database.
o public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
o public String getDatabaseProductVersion()throws SQLException: it returns the product version of the
database.
o public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[]
types)throws SQLException: it returns the description of the tables of the specified catalog. The table type
can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:

The getMetaData() method of Connection interface returns the object of DatabaseMetaData. Syntax:

public DatabaseMetaData getMetaData()throws SQLException

Simple Example of DatabaseMetaData interface :

import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());


System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());

con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions that will make the
performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may create a function that
receives date as the input and returns age of the employee as the output.

What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.

Exception handling using try/catch block can Exception handling using try/catch can't be
be used in stored procedures. used in user defined functions.

How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

Example stored procedure


Create procedure emp_age(IN emp_id int)

BEGIN

Update emp set age=23 where id=emp_id;

END

Program

Import java.sql.*;

class JdbcCallableTest

Public static void main(String args[])

try{

class.forName(“oracle.jdbc.driver.OracleDriver”);

Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”manager”);

CallableStatement csmt=con.prepareCall(“{call emp_age(101)}”);

boolean b=csmt.execute();

con.close();

}catch(Exception e)

System.out.println(e);

You might also like