0% found this document useful (0 votes)
44 views19 pages

WP Unit3

JDBC (Java Database Connectivity) is a Java API that facilitates interaction between Java applications and relational databases, providing a standard interface for executing SQL queries and retrieving results. It consists of components like the JDBC API, DriverManager, and various types of JDBC drivers (Type-1 to Type-4) for database connections. JDBC also supports transaction management, error handling, and provides methods for executing SQL commands and processing results through ResultSet objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views19 pages

WP Unit3

JDBC (Java Database Connectivity) is a Java API that facilitates interaction between Java applications and relational databases, providing a standard interface for executing SQL queries and retrieving results. It consists of components like the JDBC API, DriverManager, and various types of JDBC drivers (Type-1 to Type-4) for database connections. JDBC also supports transaction management, error handling, and provides methods for executing SQL commands and processing results through ResultSet objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-3 JDBC

JDBC OVERVIEW
JDBC (Java Database Connectivity) is a Java API that enables Java
applications to interact with databases. It provides a standard
interface for connecting to relational databases, executing SQL
queries, and retrieving results. JDBC acts as a bridge between Java
programs and database systems, allowing seamless communication
between the two.
Components of JDBC
1. JDBC API: It provides various methods and interfaces for easy
communication with the database.api .
2. JDBC Driver manager: It loads a database-specific driver in an
application to establish a connection with a database.
3. JDBC Test suite: It is used to test the operation(such as
insertion, deletion, updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the
database.

JDBC IMPLEMENTATION
 JDBC Driver: Provides the bridge between Java code and
database-specific implementations. Types include:
1. Type-1: JDBC-ODBC Bridge

 Acts as a bridge between Java applications and ODBC


(Open Database Connectivity).

 Converts JDBC calls into ODBC calls and then interacts


with the database.

2. Type-2: Native API


 Converts JDBC calls into database-specific native API
calls.
 Requires database vendor’s native libraries to be installed
on the client machine.
3. Type-3: Network Protocol
 Converts JDBC calls into a database-independent
protocol.
 Uses a middleware server that translates the protocol to
database-specific calls
4. Type-4: Thin Driver
 Directly converts JDBC calls into the database’s native
protocol.
 Written in pure Java, making it platform-independent.
 Communicates directly with the database over the
network.
Drivermanager
The DriverManager class in JDBC is part of the java.sql package
and acts as a central point for managing database drivers and
establishing connections to a database. It plays a crucial role in
managing the communication between Java applications and the
database by using the appropriate JDBC driver.
2 main responsibilities
 Driver management
 Connection management
Steps to establish a connection:
1. Load the JDBC Driver.
2. Establish a connection using DriverManager.
3. Create and execute SQL statements.
4. Process the results.
5. Close the connection.
CONNECTION CLASS
Key Responsibilities of the connection Interface

 Establishing a Connection:
o Provides methods to connect to a database.
 Transaction Management:
o Supports commit and rollback of transactions.
 Creating Statements:
o Used to execute SQL queries
o (e.g., Statement, PreparedStatement, CallableStatement).
 Database Metadata:
o Provides metadata about the database and the connection.

Methods:
1. Creating statements :
o createStatement(): Creates a Statement object.
o prepareStatement(): Used to create a PreparedStatement
object for precompiled SQL queries.
o prepareCall(String sql): Used to create a CallableStatement
object for executing stored procedures.
2. Transaction management:
o setAutoCommit(): Enables/disables auto-commit mode.
o Commit():commits the current transaction .
o Rollback():roll back the current transaction .
3. Closing the connection :
o close(): Closes the connection.
4. Metadata information :
o Getmetadata():retrives the information about the
database.
Advantages
1. Simplifies database connectivity and interaction.
2. Supports flexible transaction management.
3. Provides metadata access to understand the database schema.
Disadvantages
1. Not thread-safe; each thread requires its own Connection
object.
2. Managing connections manually can be error-prone in large-
scale applications.

STATEMENTS
Statements in JDBC are objects used to send SQL queries to a
database. They are created using a Connection object and are used
to execute SQL commands such as queries, updates, and stored
procedures.
Types of Statements in JDBC
JDBC provides three types of statements based on their usage and
efficiency:
1. Statement
 Purpose: Used for executing simple SQL queries without
parameters.
 Characteristics:
o Suitable for static SQL queries (no dynamic inputs).
o Executes the query each time without precompilation,
making it slower for repetitive queries.
 Common Methods:
o executeQuery(String sql) - Executes a SQL SELECT query
and returns a ResultSet.
o executeUpdate(String sql) - Executes INSERT, UPDATE,
DELETE, or DDL statements and returns the number of
affected rows.
o execute(String sql) - Executes any SQL statement and
returns a boolean indicating the result type.
2. PreparedStatement
 Purpose: Used for executing parameterized SQL queries.
 Characteristics:
o Precompiles SQL statements for better performance,
especially for repetitive queries.
o Prevents SQL injection attacks by separating SQL logic
from data inputs.
o Allows placeholders (?) for dynamic parameters.
 Common Methods:
o setInt(int parameterIndex, int value) - Sets an integer
value at the specified index.
o setString(int parameterIndex, String value) - Sets a string
value at the specified index.
o executeQuery() - Executes a SELECT query and returns a
ResultSet.
o executeUpdate() - Executes INSERT, UPDATE, DELETE, or
DDL statements.
3. CallableStatement
 Purpose: Used to execute stored procedures in the database.
 Characteristics:
o Suitable for executing database logic encapsulated in
stored procedures.
o Supports input, output, and input-output parameters.
 Common Methods:
o registerOutParameter(int parameterIndex, int sqlType) -
Registers an output parameter.
o setInt(int parameterIndex, int value) - Sets an integer
value for an input parameter.
o execute() - Executes the stored procedure.

CATCHING DATABASE RESULTS


 Use ResultSet object to retrieve data from a database query.
Steps to Catch Database Results
1. Establish a Connection:
o Use the DriverManager.getConnection() method to
connect to the database.
2. Create a Statement or PreparedStatement:
o Use the createStatement() or prepareStatement()
methods to define the SQL query.
3. Execute the Query:
o Use the executeQuery() method to execute SQL SELECT
queries.
4. Process the ResultSet:
o The ResultSet object holds the data returned by the query.
Iterate through the rows using next() and retrieve column
values using getter methods.
5. Close Resources:
o Close the ResultSet, Statement, and Connection objects to
free database resources.

 Methods in ResultSet:
o next():
 Moves the cursor to the next row in the ResultSet.
 Returns false if there are no more rows.
o getString(), getInt(), etc.: Retrieve data of specific
columns.
o Using coloumn index: columns can also be accessed by
their index.
o To retrieve information about the result set or database
schema, use ResultSetMetaData.
Advantages
1. Efficiently processes large amounts of data row by row.
2. Provides flexibility to navigate and manipulate result sets.
3. Metadata allows dynamic processing of results.

HANDLING DATABASE QUERIES


Handling database queries in JDBC involves the process of executing
SQL commands (such as SELECT, INSERT, UPDATE, and DELETE) and
managing the results effectively. It includes establishing a connection,
preparing and executing the queries, and managing the responses or
results.
Types of Queries Handled in JDBC
1. SELECT Queries:
o These are used to retrieve data from the database. When
you execute a SELECT query, it returns a result set that
you can process to get the required data.
2. INSERT, UPDATE, and DELETE Queries:
o These queries modify data in the database. INSERT is used
to add new records, UPDATE changes existing records, and
DELETE removes records.
3. DDL (Data Definition Language) Queries:
o These queries are used to define or modify the structure
of the database itself, such as CREATE, ALTER, or DROP
commands. These are typically executed using the
Statement object.

Managing Transactions
1. Transaction Handling:
o Transactions ensure that a series of database operations
either complete successfully together or, in the case of an
error, get rolled back. By default, JDBC operates in auto-
commit mode, meaning each individual query is treated
as a transaction.
o If you need to execute multiple queries as a single unit of
work, you can disable auto-commit, execute the queries,
and then commit or roll back the changes.
2. Commit and Rollback:
o After executing multiple SQL statements, you can call
commit() to make the changes permanent. If something
goes wrong, you can call rollback() to undo all changes
made during the transaction.

Error Handling
 When working with JDBC, it's important to handle any errors
that may occur during the database interaction. Typically, you
catch exceptions like SQLException, which provide details about
any issues encountered when executing a query or interacting
with the database.
 Proper error handling helps in debugging, logging meaningful
messages, and ensuring smooth program execution.

NETWORKING
INETADDRESS CLASS
The InetAddress class represents an IP address, both IPv4 and IPv6,
and provides methods to work with network hosts.
How it Works:
 The class provides methods that help in resolving domain
names to IP addresses and vice versa. For example, when you
type a URL like www.example.com, the InetAddress class can
resolve this hostname to an 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:
 It is a connectionless protocol.
 It utilizes less memory and the addresses can be remembered
easily with the class based addressing scheme.
 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:
 It has a stateful and stateless both configurations.
 It provides support for quality of service (QoS).
 It has a hierarchical addressing and routing infrastructure.

Key Features:
 Represents: A machine’s IP address.
 Methods:
o getByName(String host): Returns the IP address of the
host specified by the given hostname or IP address.
o getLocalHost(): Returns the InetAddress object
representing the local machine.
o getHostName(): Returns the hostname of the machine.
o getHostAddress(): Returns the IP address of the machine
as a string.
o isReachable(int timeout): Checks if the host is reachable
within the specified timeout.
Use Case:
Used to resolve hostnames to IP addresses, get local machine's
network details, and check if a remote host is reachable.
Real-World Use Case:
 Resolving hostnames for servers in client-server applications.
For example, an HTTP client will resolve the domain
www.example.com to an IP address to send an HTTP request.
 Checking if a server is reachable (before making a database call
or sending a message).

URL CLASS
The URL class represents a Uniform Resource Locator, a reference to
a resource on the Internet (e.g., http://example.com).
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.

Key Features:
 Represents: A URL for a web resource.
 Methods:
o getHost(): Returns the host name of the URL (e.g.,
www.example.com).
o getPath(): Returns the path of the resource in the URL.
o getProtocol(): Returns the protocol of the URL (e.g., http,
https).
o openStream(): Opens a connection to the resource
represented by the URL and returns an input stream.
Use Case:
The URL class is commonly used for reading web resources like HTML
files, images, or web services, or for checking or extracting details
from a URL.
Real-World Use Case:
 Downloading files from the web, such as images or data files.
 Reading content from websites, e.g., reading HTML, XML, or
JSON data from a remote service or API.

TCP SOCKETS
TCP (Transmission Control Protocol) is a connection-oriented protocol
that provides reliable, ordered communication between two
machines. In Java, TCP sockets allow programs to communicate using
this protocol.
How it Works:
 A TCP socket is created when a server listens for incoming
connections, and a client connects to it via an IP address and a
port number. Once the connection is established, data can be
sent bidirectionally over the socket.
 The server typically uses ServerSocket to listen for incoming
connections on a particular port, while the client uses Socket to
connect to the server.

Key Concepts:
 Server Side:
o A server listens for incoming connections on a specific
port.
o The server uses ServerSocket to establish a listening
socket.
 Client Side:
o A client connects to the server using Socket.
Common Classes:
 ServerSocket: Used by the server to listen for incoming
connections.
 Socket: Used by the client to communicate with the server.
Example Process:
1. Server:
o Creates a ServerSocket on a specific port.
o Waits for a client to connect using the accept() method.
o Once the client connects, a Socket object is created to
communicate.
2. Client:
o Creates a Socket object to connect to the server's IP
address and port.
o Sends and receives data using the InputStream and
OutputStream.
Use Case:
TCP sockets are used in applications that require reliable
communication, such as web servers, email clients, and chat
applications.
Real-World Use Case:
o Web Servers: HTTP uses TCP sockets to handle requests
from browsers.
o Email Clients: Protocols like SMTP (sending mail) and
POP3/IMAP (receiving mail) use TCP sockets for
communication.
o Chat Applications: Many real-time messaging applications
use TCP sockets for communication.

UDP SOCKETS
UDP (User Datagram Protocol) is a connectionless protocol. Unlike
TCP, UDP does not guarantee delivery, order, or error correction,
making it faster but less reliable.
How it Works:
 UDP does not establish a connection before sending data.
Instead, data is sent as discrete packets called datagrams.
 Each datagram is independent of others, and the receiver must
handle any loss or out-of-order packets. No acknowledgment is
sent back to the sender, making UDP faster than TCP but less
reliable.

Key Concepts:
 No connection establishment: UDP sockets do not need to
establish a connection before sending data.
 Packets: Data is sent as individual packets, which may arrive out
of order or be lost.
Common Classes:
 DatagramSocket: Used to send and receive UDP packets.
 DatagramPacket: Represents the data packets sent or received
via UDP.
Example Process:
1. Server:
o Creates a DatagramSocket.
o Receives a DatagramPacket from a client.
o Processes and sends a response.
2. Client:
o Creates a DatagramSocket.
o Sends a DatagramPacket to the server.
Use Case:
UDP is used in applications where speed is critical, and occasional
data loss is acceptable, such as real-time video streaming, DNS
queries, and online gaming.

JAVA BEANS
JavaBeans are reusable software components for Java that can be
manipulated visually in a builder tool, such as in a graphical user
interface (GUI) or a business logic layer.
How it Works:
 A JavaBean is a simple Java class that has private instance
variables, along with public getter and setter methods to access
those variables. It also typically has a no-argument constructor
and implements the Serializable interface to support
serialization.
Key Features:
 Encapsulation: JavaBeans follow the principles of
encapsulation, with private properties and public getter/setter
methods.
 Serializable: Beans should implement the Serializable interface
to support persistence.
 No-argument Constructor: JavaBeans must provide a no-
argument constructor for instantiation.
Use Case:
JavaBeans are widely used for data encapsulation in applications,
particularly for handling form data, JavaServer Pages (JSP), and
Enterprise JavaBeans (EJB) for server-side applications.
Real-World Use Case:
 Enterprise Applications: JavaBeans are often used for
encapsulating business logic or data for use in enterprise
applications, such as in JavaServer Pages (JSP) or Java Enterprise
Edition (JEE).
 Form Data: In web applications, JavaBeans are often used to
represent form data submitted by the user.
 Configuration: JavaBeans are used in frameworks like Spring for
dependency injection and configuration management.

RMI (REMOTE METHOD INVOCATION)


RMI allows Java programs to invoke methods on an object that is
running on a different machine (remote communication). RMI
abstracts the complexity of network communication and enables
remote procedure calls between different JVMs.
How it Works:
 RMI allows for communication between distributed objects.
The client can invoke methods on a remote object as if it were
local. RMI abstracts the details of networking and allows you to
interact with remote objects in a seamless way.
 RMI uses stubs and skeletons (in older versions) to handle
communication. The client communicates with a stub, which
forwards requests to the server, where the skeleton used to
handle the communication.
Key Concepts:
 Remote Interface: An interface that defines the methods that
can be invoked remotely. The interface extends
java.rmi.Remote and methods must throw RemoteException.
 Stub and Skeleton: Stubs are client-side proxies that forward
method calls to the remote server, while skeletons handle the
invocation on the server side (in modern RMI implementations,
the skeleton is no longer needed).
 RMI Registry: A naming service that allows clients to look up
remote objects by name.
 RMI Server: A server that registers remote objects with the RMI
Registry.

Steps:
1. Define a remote interface.
2. Implement the remote interface in a remote class.
3. Bind the remote object to the RMI registry.
4. On the client side, look up the remote object in the registry and
invoke methods on it.

Use Case:
RMI is used in distributed applications, such as in enterprise-level
applications or systems that require inter-process communication
between Java applications on different machines.
Real-World Use Case:
 Distributed Applications: RMI is ideal for building Java-based
distributed applications where different machines in a network
need to communicate and perform operations remotely, such
as in financial systems, cloud computing, and enterprise
applications.
 Remote Management: Managing remote resources like
databases, file systems, or virtual machines can be done using
RMI.

You might also like