You are on page 1of 16

Remote Method Invocation (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.
•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 •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 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 −
To write an RMI Java application, you would have to follow the steps given below
– 1.Define the remote interface 2.Develop the implementation class (remote object)
3.Develop the server program 4.Develop the client program 5.Compile the
application6.Execute the application Defining the Remote Interface
A remote interface provides the description of all the methods of a particular remote
object. The client communicates with this remote interface.
To create a remote interface −•Create an interface that extends the predefined
interface Remote which belongs to the package.•Declare all the business methods
that can be invoked by the client in this interface.•Since there is a chance of network
issues during remote calls, an exception named RemoteException may occur;
throw it. Following is an example of a remote interface. Here we have defined an
interface with the name Hello and it has a method called printMsg().
import java.rmi.Remote; import java.rmi.RemoteException;
interface Hello extends Remote { void printMsg() throws
RemoteException; }
Developing the Implementation Class (Remote Object) We need to implement
the remote interface created in the earlier step. (We can write an implementation
class separately or we can directly make the server program implement this
interface.) To develop an implementation class −
•Implement the interface created in the previous step.
•Provide implementation to all the abstract methods of the remote interface.
Following is an implementation class. Here, we have created a class named
ImplExample and implemented the interface Hello created in the previous
step and provided body for this method which prints a message.
public class ImplExample implements Hello {
public void printMsg() {
System.out.println("This is an example RMI program"); } }
Developing the Server Program
An RMI server program should implement the remote interface or extend the
implementation class. Here, we should create a remote object and bind it to the
RMIregistry. To develop a server program −
•Create a server class from where you want invoke the remote object.
•Create a remote object by instantiating the implementation class as shown below.
•Export the remote object using the method exportObject() of the class named
UnicastRemoteObject which belongs to the package java.rmi.server.
•Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
•Bind the remote object created to the registry using the bind() method of the class named
Registry. To this method, pass a string representing the bind name and the object exported,
as parameters. import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends ImplExample { public Server() {}
public static void main(String args[]) { try {
ImplExample obj = new ImplExample(); object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub); System.err.println("Server ready"); }
catch (Exception e) {System.err.println("Server exception: " + e.toString());
e.printStackTrace(); } } } Developing the Client Program
Write a client program in it, fetch the remote object and invoke the required method using
this object. To develop a client program −
•Create a client class from where your intended to invoke the remote object.
•Get the RMI registry using the getRegistry() method of the LocateRegistry
class which belongs to the package java.rmi.registry.
•Fetch the object from the registry using the method lookup() of the class Registry which
belongs to the package java.rmi.registry.
•To this method, you need to pass a string value representing the bind name as a
parameter. This will return you the remote object.
•The lookup() returns an object of type remote, down cast it to the type Hello.
•Finally invoke the required method using the obtained remote object.
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry;
public class Client { private Client() {} public static void main(String[] args)
{ try { Registry registry = LocateRegistry.getRegistry(null);
Hello stub = (Hello) registry.lookup("Hello"); stub.printMsg();
System.out.println("Remote method invoked"); }
catch (Exception e) { System.err.println("Client exception: " + e.toString());
e.printStackTrace(); } }}
Unit-6 Networking
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.
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.

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.
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.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.
Java 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
•DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
•DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
•DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.
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
•DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
•DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.
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(), s tr.length(), ip, 3000);
ds.send(dp); ds.close(); } }
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(); } }
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.
ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes
connection and waits for the client
Socket class A socket is simply an endpoint for communications
between the machines. The Socket class can be used to create a socket.
ServerSocket class The ServerSocket class can be used to create a
server socket. This object is used to establish communication with 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. Socket s=new Socket("localhost",6666);
my server.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();
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);} } }
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);} } }
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.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.
IP Address • An IP address helps to identify a specific resource on the network
using a numerical representation. • 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 2 32 addresses that is more than 4 million
addresses.
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).
TCP/IP Protocol •TCP/IP is a communication protocol model used connect
devices over a network via internet. •TCP/IP helps in the process of addressing,
transmitting, routing and receiving the data packets over the internet. •The two
main protocols used in this communication model are: • 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. • 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..
import java.io.*; import java.net.*; public class InetDemo{
public static void main(String[] args){
try{ InetAddress ip=InetAddress.getByName("www .javatpoint.com");
System.out.println("Host Name: "+ip.getHostN ame());
System.out.println("IP Address: "+ip.getHostA ddress()); }
catch(Exception e){ System.out.println(e);} }
• 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 •DatagramSocket() throws
SocketEeption: it creates a datagram socket and binds it with the available Port Number
on the localhost machine. •DatagramSocket(int port) throws SocketEeption: it creates a
datagram socket and binds it with the given Port Number. •DatagramSocket(int port,
InetAddress address) throws SocketEeption: it creates a datagram socket and binds it
with the specified port number and host address.
• 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 •DatagramPacket(byte[] barr, int length): it creates a datagram
packet. This constructor is used to receive the packets. •DatagramPacket(byte[] barr,
int length, InetAddress address, int port): it creates a datagram packet. This constructor
is used to send the packets.
//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(), s tr.length(), ip, 3000);
ds.send(dp); ds.close(); } } //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(); } }
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5
following steps.
Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver
Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sppu 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 sppu is the database name. We may use
any database, in such case, we need to replace the sppu with our database
name.
Username: The default username for the mysql database is root.
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
In this topic, we are using MySql as the database. So we need to know following
information's for the mysql database:
SQL Queries
• SELECT column1, column2, ... FROM table_name;
• SELECT column1, column2, ... FROM table_name WHERE condition;
• INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1,
value2, value3, ...);
• INSERT INTO table_name VALUES (value1, value2, value3, ...);
• UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;
• DELETE FROM table_name WHERE condition;
javax.sql The javax,sql package is also called as the JDBC extension API, and
provides classes and interfaces to access server-side data sources and process
Java Programs. The JDBC extension package supplements the java.sql package
and provide the following support,
1)DataSource 2) Connection and Statement Pooling 3)Distributed transaction 4)
Rowsets
Grid Layout is a CSS module that allows you to create complex web page layouts with
ease. It provides a two-dimensional grid system that organizes elements into rows
and columns. Each element can be positioned precisely within the grid, making it a
powerful tool for designing responsive and flexible web layouts.
Key Features of Grid Layout:
1. Grid Container: The parent element that contains the grid items. It is defined using
the display: grid; property.
2. Grid Items: The child elements that are placed inside the grid container. They can
be positioned within the grid using various grid-related properties.
3. Grid Rows and Columns: The grid is divided into rows and columns, which can be
defined explicitly or automatically adjusted based on content.
4. Grid Lines: Horizontal and vertical lines that define the boundaries of rows and
columns within the grid.
5. Grid Tracks: The space between two adjacent grid lines, creating rows and columns.
6. Grid Areas: Named areas within the grid that can be assigned to grid items,
allowing for easy placement and alignment.
7. Grid Gaps: Spaces between grid tracks, specifying the size of the gap between rows
and columns.
htmlCopy code <!DOCTYPE html> <html><head><style>
.grid-container { grid-gap: 10px;
display: grid; grid-template-columns: 1fr 1fr 1fr;
}.grid-item { background-color: #ccc;
padding: 20px; text-align: center; }</style></head> <body>
<div class="grid-container"><div class="grid-item">Item 1</div>
<div class="grid-item">Item 2</div> <div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div><div class="grid-item">Item 5</div>
<div class="grid-item">Item 6</div></div></body></html>
1. FlowLayout:
• FlowLayout is a simple layout manager that arranges components in a left-to-right
flow, wrapping them to the next line when the container's width is exceeded.
• It is commonly used when you want components to be displayed in a linear manner,
similar to text flowing in a paragraph.
• Key Features:
• Components are added from left to right.
• When the container width is exceeded, components wrap to the next line.
Components maintain their preferred sizes.
• Supports vertical alignment (top, center, bottom) and horizontal alignment (left,
center, right).
• Example Usage: Creating a toolbar with buttons arranged horizontally
AWT Components
AWT (Abstract Window Toolkit) is a core part of Java's original GUI
toolkit. AWT provides a set of classes and interfaces for creating and
managing graphical user interfaces in Java applications. AWT
components are the building blocks of user interfaces, representing
various graphical elements such as buttons, labels, text fields, and
more. Here, we'll explain some commonly used AWT components:
1. Button:• The Button class represents a push-button component that
triggers an action when clicked.It can display text or an image and can
be customized with different styles and sizes.• Example usage: Creating
a button to submit a form or perform an action.
2. Label:• The Label class is used to display a non-editable text or an
image.
It provides a way to present static information or titles in a user
interface
• Example usage: Displaying a title or description in a form or dialog.
3. TextField:• The TextField class provides a single-line text input field
for user input
• Users can enter and edit text in this component.• Example usage:
Accepting user input for names, email addresses, or other textual data.
4. TextArea:The TextArea class represents a multiline text input field.
• It allows users to enter and edit multiple lines of text.
Example usage: Accepting user input for longer descriptions,
comments, or messages.
5. Checkbox:• The Checkbox class represents a checkbox component
that allows users to select multiple options.
It can be used in groups to present a list of selectable choices.•
Example usage: Creating a list of options where users can choose
multiple items.
6. RadioButton• The RadioButton class represents a radio button
component that allows users to select a single option from a group of
choices.
• Only one radio button can be selected at a time within a group.
Write a program to add Three Menu Item and One Sub Menu to Menu,add two
Menuitem to SubMenu and add
import java.awt.*; import javax.swing.*; public class MenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Menu Example");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JMenuBar
menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu"); JMenuItem item1 = new
JMenuItem("Item 1");
JMenuItem item2 = new JMenuItem("Item 2");
JMenuItem item3 = new JMenuItem("Item 3"); menu.add(item1);
menu.add(item2); menu.add(item3);
JMenu subMenu = new JMenu("Sub Menu");
JMenuItem subMenuItem1 = new JMenuItem("Item 4");
JMenuItem subMenuItem2 = new JMenuItem("Item 5");
subMenu.add(subMenuItem1); subMenu.add(subMenuItem2);
menu.add(subMenu); menuBar.add(menu);
frame.setJMenuBar (menuBar); frame.setSize(300, 200);
frame.setVisible(true); }}
In the above example, we create a JFrame to hold our graphical user interface. We
create a JMenuBar called menuBar and a Menu called menu. We then create three
JMenuItem objects (item1, item2, item3) and add them to the main menu using the
add() method.
Next, we create a sub-menu called submenu using JMenu and two sub-menu items
(subMenuItem1, subMenuItem2) using JMenuItem. We add these sub-menu items to
the sub-menu using the add() method.
Finally, we add the sub-menu to the main menu using add() and add the main menu
to the menu bar using add(). We set the menu bar to the frame using set JMenuBar(),
and set the size and visibility of the frame.
When you run this program, it will create a window with a menu bar that has the
"Menu" menu. The "Menu" menu contains three menu items ("Item 1", "Item 2",
"Item 3") and a sub-menu called "Sub Menu". The sub-menu contains two sub-menu
items ("Item 4", "Item 5").
i) Hashing in Java
Hashing is a technique used in Java (and other programming languages) to efficiently
store and retrieve data from data structures like hash tables or hash maps. It involves
mapping data to a fixed-size value, called a hash code or hash value, using a hash
function. Here's a short note on hashing in Java:
• Hash Function: A hash function takes an input (data) and produces a unique hash
code of a fixed length. The hash function should generate the same hash code for the
same input consistently.
Hash Code: The hash code is an integer value that represents the input data after
applying the hash function. It serves as an index or key to store and retrieve data in
hash-based data structures.
• Hash-based Data Structures: Hashing is commonly used in data structures like hash
tables, hash maps, or hash sets. These data structures store data based on their hash
codes, enabling fast access and retrieval of values.
• Collision Handling: Hashing can lead to collisions, where two different inputs
produce the same hash code. Collisions are handled using collision resolution
techniques like chaining or open addressing, ensuring that multiple values can be
stored and retrieved correctly.
• Efficiency: Hashing allows for constant-time average case complexity for insertion,
deletion, and retrieval operations in hash-based data structures. It provides a fast and
efficient way to manage large amounts of data.
) java.util Package : The java.util package is a fundamental package in Java that
provides a collection of utility classes and interfaces. It contains various classes and
interfaces that offer commonly used functionalities and data structures. Here's a
short note on the java.util package• Collections: The java.util package includes classes
and interfaces for working with collections, such as List, Set, Map, and their
implementations (ArrayList, HashSet, HashMap, etc.). These collections provide
convenient ways to store, manipulate, and iterate over groups of objects.• Utilities:
The package provides utility classes like Arrays, Collections, and objects. These classes
offer methods for sorting arrays, searching elements, shuffling collections, performing
conversions, and more.Date and Time. The java.util package includes classes for
working with dates and times, such as Date, Calendar, DateFormat, and
SimpleDateFormat. These classes enable operations like date formatting, parsing, and
manipulation.• Random Numbers: The package provides the Random class for
generating random numbers. It offers methods to generate random integers, doubles,
booleans, and more, allowing for various randomization needs in Java programs.
What is database connection? Explain how to connect JDBC
1. Load the JDBC Driver: Before interacting with the database, you need to load the
JDBC driver specific to your database. This step is typically accomplished by loading
the driver class using Class.forName(). For example, for MySQL, you would load the
driver class as follows: Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection: Create a connection to the database using the
DriverManager.getConnection() method. You need to provide the database URL,
username, and password as parameters. For example:
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username= "myusername"; String password = "mypassword";
Connection connection DriverManager.getConnection(url, username, password);
3. Create a Statement: Once you have a connection, create a statement object to
execute SQL commands. Use the createStatement() method of the Connection object
to create a statement. For example:
Statement statement connection.createStatement();
4. Execute SQL Commands: Use the execute(), executeUpdate(), or executeQuery()
methods of the Statement object to execute SQL commands.
• The execute() method is used for executing SQL commands that do not return any
result, such as CREATE, INSERT, UPDATE, or DELETE statements. It returns a boolean
indicating if the command executed successfully.
• The executeUpdate() method is used executing SQL commands modify data, such
as INSERT, UPDATE, or DELETE statements. It returns the number of affected rows.
• The executeQuery() method is used for executing SQL queries that retrieve data,
such as SELECT statements. It returns a ResultSet object containing the retrieved data.
For Eg. to execute a simple SELECT statement: String sql = "SELECT * FROM
customers"; ResultSet resultSet = statement.executeQuery(sql);
5. Process the Results: If you executed a query and obtained a ResultSet, you can
process the retrieved data using methods like next(), getString(), getInt(), etc. For
example: while (resultset.next()) { String name = resultSet.getString("name");
int age = resultSet.getInt("age"); // Process the retrieved data }
6. Close the Resources: After executing the SQL commands and processing the
results, it's important to close the resources properly. Close the ResultSet, Statement,
and Connection objects in the reverse order of their creation. This can be done using
the close() method. For example:
resultset.close(); connection.close(); statement.close();
By following these steps, you can execute SQL commands and interact with a
database using JDBC in Java. Remember to handle exceptions appropriately and
ensure proper resource management to avoid memory leaks and database
connection issues.
CallableStatement in JDBC
In JDBC (Java Database Connectivity), a CallableStatement is a subinterface of
PreparedStatement and is used to execute stored procedures or database functions. It
allows you to execute SQL statements that are precompiled and stored in the
database. The CallableStatement provides a way to pass input parameters, retrieve
output parameters, and obtain the result sets returned by the stored procedure or
function. Here's an explanation of CallableStatement with a suitable example:
Example: Let's consider a scenario where we have a stored procedure called get
EmployeeDetails in the database, which takes an employee ID as input and retrieves
the employee's details from the "Employees" table.
1. Preparation: First, establish a database connection using
DriverManager.getConnection() as explained in the previous answer.
2. Create CallableStatement: Create a CallableStatement object by calling the
prepareCall() method of the Connection object. Pass the SQL statement that calls the
stored procedure as a parameter. For example:
CallableStatement callableStatement = connection.prepareCall("(call
getEmployeeDetails (?)}");
3. Set Input Parameters: If the stored procedure has any input parameters, you can
set their values using the setxxx() methods of the CallableStatement, where xxx
corresponds to the data type of the input parameter. For example, if the stored
procedure takes an employee ID as input:
int employeeId = 123; callableStatement.setInt(1, employeeId);
4. Register Output Parameters: If the stored procedure has output parameters, you
need to register them using the registerOutParameter() method of the
CallableStatement. Specify the parameter index and the SQL data type of the output
parameter. For example, if the stored procedure has an output parameter for the
employee's name: javaCopy code callableStatement.registerOutParameter
5. Execute the CallableStatement: Use the execute() or executeQuery() method of
the CallableStatement to execute the stored procedure. If the stored procedure
returns a result set, use executeQuery(); otherwise, use execute().
javaCopy code boolean hasResultSet = callableStatement.execute();
6. Retrieve Output Parameters: If the stored procedure has output parameters, you
can retrieve their values using the getxxx() methods of the CallableStatement. For
example, to retrieve the employee name:
javaCopy code String employeeName = callableStatement.getString(2);
Driver Types of JDBC:
JDBC provides different driver types, each defining the method by which Java
applications interact with the database. There are four types of JDBC drivers!
Type 1: JDBC-ODBC Bridge Driver
Also known as the "JDBC-ODBC Bridge" driver.
This driver uses the ODBC (Open Database Connectivity) API to connect Java
applications to databases.
It relies on an existing ODBC driver to convert JDBC method calls into ODBC calls.
• This driver is platform-dependent and requires the presence of an ODBC driver
manager and ODBC driver.
• Example: sun.jdbc.odbc.Jdbc0dbcDriver.
. Type 2: Native-API Driver
Also known as the "Native Driver" or "Partially Java Driver".
This driver uses a database-specific API provided by the database vendor to establish
a connection
• It combines Java code with the database-specific native code (C, C++, etc.) to access
the database.
This driver offers better performance compared to the JDBC-ODBC Bridge driver. •
Example: Oracle OCI (Oracle Call Interface) driver.
Type 3: Network Protocol Driver
• Also known as the "Network Driver" or "Middleware Driver".
• This driver communicates with a middleware server (middleware software) that acts
as an intermediary between the Java application and the database.
• The middleware server converts JDBC calls into a database-specific protocol and
forwards them to the database server. • It allows Java applications to connect to
different databases without requiring database-specific code.
• Example: IBM DB2 Universal Database (UDB) JDBC driver.
Type 4: Thin Driver
Also known as the "Pure Java Driver" or "Direct-to-Database Driver"
• This driver communicates directly with the database server using a database-
specific protocol.
• It is entirely written in Java and does not require any additional software or
middleware.
This driver offers better performance, portability, and security compared to other
driver types.
• Example: MySQL Connector/J driver.

You might also like