0% found this document useful (0 votes)
53 views7 pages

Understanding JDBC Architecture and Components

JDBC is a Java API that allows Java programs to connect to databases. It uses drivers to provide a standard interface to different database management systems. There are four types of JDBC drivers: Type 1 uses ODBC, Type 2 uses a database's native API, Type 3 uses a middleware application server, and Type 4 is a 100% pure Java driver provided by the database vendor. To create a JDBC application, a program must import SQL packages, register a driver, open a connection, execute queries, and close resources. Statements are used for basic SQL, PreparedStatements are for parameterized SQL, and CallableStatements are for stored procedures. ResultSets contain the results of queries.

Uploaded by

Waseem Shaikh
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)
53 views7 pages

Understanding JDBC Architecture and Components

JDBC is a Java API that allows Java programs to connect to databases. It uses drivers to provide a standard interface to different database management systems. There are four types of JDBC drivers: Type 1 uses ODBC, Type 2 uses a database's native API, Type 3 uses a middleware application server, and Type 4 is a 100% pure Java driver provided by the database vendor. To create a JDBC application, a program must import SQL packages, register a driver, open a connection, execute queries, and close resources. Statements are used for basic SQL, PreparedStatements are for parameterized SQL, and CallableStatements are for stored procedures. ResultSets contain the results of queries.

Uploaded by

Waseem Shaikh
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 1: JDBC (Java Database Connectivity)

JDBC is a standard Java API for a database-independent connectivity between the Java
programming language and a wide range of databases. This application program interface lets
you encode the access request statements, in Structured Query Language (SQL). They are
then passed to the program that manages the database. It mainly involves opening a
connection, creating a SQL Database, executing SQL queries and then arriving at the output.
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 databases.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The driver manager is capable of supporting
multiple concurrent drivers connected to multiple heterogeneous databases.

Common JDBC Components


The JDBC API provides the following interfaces and classes −

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 1


DriverManager is used to manage a list of database drivers. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database Connection.
Driver is an interface that handles the communications with the database server. It also
abstracts the details associated with working with Driver objects.
Connection is an interface that consists all the methods required to connect to a database. The
connection object represents communication context, i.e., all communication with the
database is through connection object only.

JDBC Driver Types


JDBC drivers are used to implement the defined interfaces in the JDBC API, for interacting
with the database server. A JDBC driver does three things and they are as follows:
1. Establishes a connection with a data source.
2. It will send queries and update statements to the data source.
3. Finally, it processes the results.
There are 4 types of drivers, namely:
Type 1: JDBC-ODBC Bridge Diver
In Type 1 driver, a JDBC bridge accesses ODBC drivers installed on each client machine.
Further, ODBC configures Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed
on each client machine.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 2


The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS and forwarded to the database server.

This kind of driver is extremely flexible since it requires no code installed on the client and a
single driver can actually provide access to multiple databases. You can think of the
application server as a JDBC “proxy,” meaning that it makes calls for the client application.
As a result, you need some knowledge of the application server’s configuration in order to
effectively use this driver type. Your application server might use a Type 1, 2, or 4 drivers to
communicate with the database.
Type 4: 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor’s
database through a socket connection. This is the highest performance driver available for the
database and is usually provided by the vendor itself.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 3


This kind of driver is extremely flexible, you don’t have to install special software on the
client or server. Further, these drivers can be downloaded dynamically.
MySQL’s Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Steps to create JDBC Application


In order to create JDBC Application, we need to follow few steps.

1) Import the packages:


You need to include the packages containing the JDBC classes needed for database
programming. Most often, using import [Link].* will suffice.
2) Register the JDBC driver:
Here you have to initialize a driver so that you can open a communication channel with the
database.
3) Open a connection:
Here, you can use the getConnection() method to create a Connection object, which
represents a physical connection with the database.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 4


4) Execute a query:
Requires using an object of type Statement for building and submitting an SQL statement to
the database.
Extract data from result set: Requires that you use the appropriate getXXX() method to
retrieve the data from the result set.
5) Clean up the environment:
Requires explicitly closing all database resources versus relying on the JVM’s garbage
collection.
Statement, PreparedStatement & CallableStatement in Java:
JDBC API provides 3 different interfaces to execute the different types of SQL queries. They
are,
1) Statement
Statement interface is used to execute normal SQL queries. You can’t pass the parameters
to SQL query at run time using this interface

Example:

//Creating The Statement Object

Statement stmt = [Link]();

//Executing The Statement

[Link]("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME


VARCHAR)");

2) PreparedStatement
PreparedStatement is used to execute dynamic or parameterized SQL queries.
PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface
//Creating PreparedStatement object
PreparedStatement pstmt = [Link]("update STUDENT set NAME = ? where
ID = ?");
//Setting values to place holders using setter methods of PreparedStatement object
[Link](1, "MyName"); //Assigns "MyName" to first place holder
[Link](2, 111); //Assigns "111" to second place holder
//Executing PreparedStatement
[Link]();
3) CallableStatement

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 5


CallableStatement is used to execute the stored procedures. CallableStatement extends
PreparedStatement. Usng CallableStatement, you can pass 3 types of parameters to stored
procedures. They are : IN – used to pass the values to stored procedure, OUT – used to hold
the result returned by the stored procedure and IN OUT – acts as both IN and OUT
parameter.
//Creating CallableStatement object
CallableStatement cstmt = [Link]("{call anyProcedure(?, ?, ?)}");
//Use [Link]() methods to pass IN parameters
//Use [Link]() method to register OUT parameters
//Executing the CallableStatement
[Link]();
//Use [Link]() methods to retrieve the result returned by the stored procedure

Statement Vs PreparedStatement Vs CallableStatement In Java:

ResultSet
A ResultSet is a Java object that contains the results of executing an SQL query. In other
words, it contains the rows that satisfy the conditions of the query. The data stored in a
ResultSet object is retrieved through a set of get methods that allows access to the various

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 6


columns of the current row. The [Link] method is used to move to the next row of the
ResultSet, making it the current row.

The general form of a result set is a table with column headings and the corresponding values
returned by a query.
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.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 7

Common questions

Powered by AI

The four types of JDBC drivers each have distinct characteristics impacting application deployment and performance. Type 1 drivers, known as JDBC-ODBC Bridge Drivers, rely on ODBC connections and are recommended only for experimental use due to their limited performance . Type 2 drivers, or JDBC-Native API drivers, convert JDBC calls into database-specific native calls, which require vendor-specific drivers to be installed on each client machine, compromising deployment flexibility and often reducing portability . Type 3 drivers, JDBC-Net pure Java drivers, use a three-tier approach with a middleware application server, providing flexible deployment with the potential to access multiple database types and reduce the need for database-specific client configurations, yet possibly increasing latency . Finally, Type 4 drivers, also known as 100% Pure Java drivers, offer the best performance by providing direct connectivity between Java applications and the database, while eliminating the need for client-side installations and enhancing portability and scalability, typically being the preferred option .

DriverManager in JDBC acts as a service that manages the list of database drivers available for an application. It plays a crucial role in establishing database connections by selecting the appropriate driver from the available ones that recognize a specific database URL's subprotocol . When a database connection request is made, DriverManager iterates over the registered drivers to find one that can connect to the desired database, ensuring that applications can connect to different databases transparently. This mechanism allows an application to use multiple concurrent drivers to interact with various database systems without needing the application code to change for each database type .

The ResultSet interface in JDBC facilitates data retrieval by allowing applications to access the data obtained from executing a SQL query. It provides methods to navigate through the data and retrieve information from the current row, emulating a table structure with columns and rows . Common methods used for navigation include next(), which advances the cursor to the next row; previous(), to move back to the previous row; first() and last(), to jump directly to the first and last rows, respectively . These methods enable iterative data processing within the result set, allowing applications to handle query results dynamically and efficiently .

Closing database resources in JDBC applications is crucial for ensuring efficient resource management and application stability. If database resources like Connection, Statement, and ResultSet objects are not closed properly, they remain allocated, consuming memory and other resources, which can lead to resource leaks and eventually cause the application to run out of memory or fail to open new connections . Improper resource management may also lead to database locks remaining active longer than necessary, causing contention issues and affecting the performance of other operations. Therefore, explicitly closing resources as soon as they are no longer needed helps maintain application performance, avoid memory leaks, and ensure a stable database environment .

Setting up a JDBC application involves several critical steps: Importing the necessary JDBC packages, which provide the classes and interfaces required for database operations, ensuring the application can compile and interact with databases . Registering the JDBC driver is essential for opening a communication channel with the database, without which the application cannot establish a connection . Opening a connection using the getConnection() method creates a physical link to the database, allowing SQL queries to be executed . Executing a query involves using Statement objects to send SQL queries to the database and retrieve results . Finally, cleaning up the environment is crucial to releasing database resources and ensuring that connections are closed properly, preventing resource leaks and potential application crashes . Each step ensures that the application can reliably and efficiently interact with the database.

A Type 3 JDBC driver would be more beneficial over a Type 2 driver in scenarios where a three-tier application architecture is employed, and there is a need to maintain flexibility and adaptability in database interactions. Type 3 drivers use a middleware application server to translate JDBC calls, offering the advantage of not requiring client-side database-specific driver installations, thus simplifying client deployment and maintenance . They are also beneficial when an application needs to connect to multiple databases through the same driver, as the middleware can handle communication with different database types. Conversely, Type 2 drivers would require client-specific installations and are typically optimal for niche environments where performance for a specific database takes precedence over flexibility .

Statement, PreparedStatement, and CallableStatement are used for different scenarios in JDBC. Statement is suited for executing simple and static SQL queries where no parameters need to be supplied at runtime; this is straightforward but offers no support for dynamic queries . PreparedStatement is used for dynamic or parameterized queries; it allows parameters to be set dynamically, improving code reusability and reducing the risk of SQL injection attacks . CallableStatement is designed for executing stored procedures in a database and can use IN, OUT, and INOUT parameters to pass inputs and retrieve outputs from the procedure, making it ideal for accessing complex data operations efficiently on the server side . Each has advantages based on query complexity and the need for dynamic inputs, security, and efficiency in executing database logic.

The JDBC architecture facilitates connectivity between Java applications and relational databases by providing a uniform interface for SQL-based database interaction. Its key components include the JDBC API and the JDBC Driver API. The JDBC API allows applications to connect to different databases in a platform-independent way, by using a driver manager to load specific drivers for each database . These drivers handle the conversion of Java function calls into protocol-specific calls understood by the databases. The architecture supports both two-tier and three-tier models and includes components such as DriverManager for managing available drivers, Connection interface for establishing connections, and various driver types for specific deployment scenarios .

CallableStatement enhances the execution of stored procedures in JDBC by providing a direct and efficient interface for calling procedures stored in a database. Unlike Statement and PreparedStatement, CallableStatement is specifically designed for executing stored procedures, allowing for the use of IN, OUT, and INOUT parameters to interact with database procedures . This functionality facilitates the execution of complex database operations that are encapsulated in stored procedures, enabling more secure and efficient query operations, better performance, and reusable logic on the database server. It also allows applications to leverage database-specific functionalities, such as complex calculations or batch processing, which may be cumbersome or inefficient to replicate directly within application code .

Using PreparedStatement over Statement in JDBC applications significantly enhances security by mitigating SQL injection risks. Unlike Statement, which executes SQL queries as plain text directly, thus exposing the application to SQL injection if user-supplied data is concatenated into queries, PreparedStatement allows parameters to be set dynamically using placeholder syntax . The parameter values are bound to these placeholders, separating them from the SQL logic. This separation ensures that even if user input is malicious, it cannot alter the SQL command structure, preventing unauthorized access or data manipulation . Consequently, PreparedStatement provides an additional layer of security by safeguarding against one of the most common and dangerous database vulnerabilities.

You might also like