JDBC(upadated)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

JDBC

Interaction of Java with Databases


Java Database Connectivity
• The JDBC API is a Java API that can access any kind of tabular
data, especially data stored in a relational database.
• JDBC helps you to write Java applications that manage these
three programming activities:
1.Connect to a data source, like a database
2.Send queries and update statements to the database
3.Retrieve and process the results received from the database in
answer to your query
JDBC Example Code
• public void connectToAndQueryDatabase(
• String username,String password) {
• Connection con = DriverManager.getConnection(
• "jdbc:myDriver:myDatabase",username,password);
• Statement stmt = con.createStatement();
• ResultSet rs = stmt.executeQuery("SELECT
• a, b, c FROM Table1");
• while (rs.next()) {
• int x = rs.getInt("a");
• String s = rs.getString("b");
• float f = rs.getFloat("c");
• }
• }
Working of JDBC code
• Last slide code fragment instantiates a DriverManager
• object to connect to a database driver and log into
• the database,
• instantiates a Statement object that
• carries your SQL language query to the database;
• instantiates a ResultSet object that retrieves the
• results of your query,
• and executes a simple
• while loop, which retrieves and displays
• those results. It's that simple.
JDBC Product Components

• The JDBC API — The JDBC™ API provides programmatic


access to relational data from the Java™ programming
language. Using the JDBC API, applications can execute SQL
statements, retrieve results, and propagate changes back to
an underlying data source. The JDBC API can also interact
with multiple data sources in a distributed, heterogeneous
environment.
• The JDBC API is part of the Java platform, which includes the
Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise
Edition (Java™ EE). The JDBC 4.0 API is divided into two
packages: java.sql and javax.sql. Both packages are included
in the Java SE and Java EE platforms.
JDBC Product Components

• JDBC Driver Manager — The JDBC DriverManager class


defines objects which can connect Java applications to a
JDBC driver. DriverManager has traditionally been the
backbone of the JDBC architecture. It is quite small and
simple.
• The Standard Extension packages javax.naming and
javax.sql let you use a DataSource object registered
with a Java Naming and Directory Interface™ (JNDI)
naming service to establish a connection with a data
source. You can use either connecting mechanism, but
using a DataSource object is recommended whenever
possible
JDBC Product Components
• JDBC Test Suite — The JDBC driver test suite helps you
to determine that JDBC drivers will run your program.
These tests are not comprehensive or exhaustive, but
they do exercise many of the important features in the
JDBC API.
• JDBC-ODBC Bridge — The Java Software bridge provides
JDBC access via ODBC drivers. Note that you need to
load ODBC binary code onto each client machine that
uses this driver. As a result, the ODBC driver is most
appropriate on a corporate network where client
installations are not a major problem, or for application
server code written in Java in a three-tier architecture.
What is API?
• API stands for Application Programming Interface. It is
essentially a set of rules and protocols which transfers
data between different software applications and allow
different software applications to communicate with
each other. Through an API one application can request
information or perform a function from another
application without having direct access to it’s
underlying code or the application data.
• JDBC API uses JDBC Drivers to connect with the
database.
JDBC Drivers
• JDBC drivers are client-side adapters (installed on the
client machine, not on the server) that convert requests
from Java programs to a protocol that the DBMS can
understand. There are 4 types of JDBC drivers:
1.Type-1 driver or JDBC-ODBC bridge driver
2.Type-2 driver or Native-API driver (partially java driver)
3.Type-3 driver or Network Protocol driver (fully java
driver)
4.Type-4 driver or Thin driver (fully java driver)
JDBC-ODBC bridge driver – Type 1 driver

Type-1 driver or 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.
Type-1 driver is also called Universal driver because it can be used to connect to any of
the databases.
JDBC-ODBC bridge driver – Type 1
driver
• Advantages
• This driver software is built-in with JDK so no need to install
separately.
• It is a database independent driver.
• Disadvantages
• As a common driver is used in order to interact with different
databases, the data transferred through this driver is not so secured.
• The ODBC bridge driver is needed to be installed in individual client
machines.
• Type-1 driver isn’t written in java, that’s why it isn’t a portable
driver.
Native-API driver – Type 2 driver ( Partially Java
driver)

• The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into
native calls of the database API. In order to interact with
different database, this driver needs their local API, that’s
why data transfer is much more secure as compared to
type-1 driver. This driver is not fully written in Java that is
why it is also called Partially Java driver.

Advantage
• Native-API driver gives better performance than JDBC-
ODBC bridge driver.
Native-API driver – Type 2 driver ( Partially Java
driver)

Disadvantages
•Driver needs to be installed separately in individual client machines
•The Vendor client library needs to be installed on client machine.
•Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
•It is a database dependent driver.
Network Protocol driver – Type 3 driver (fully
Java driver)

• The Network Protocol driver uses middleware (application server)


that converts JDBC calls directly or indirectly into the vendor-
specific database protocol. Here all the database connectivity
drivers are present in a single server, hence no need of individual
client-side installation.
• Advantages
• Type-3 drivers are fully written in Java, hence they are portable
drivers.
• No client side library is required because of application server that
can perform many tasks like auditing, load balancing, logging etc.
• Switch facility to switch over from one database to another
database.
Network Protocol driver – Type 3
driver (fully Java driver)

Disadvantages
•Network support is required on client machine.
•Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in the
middle tier.
Thin driver – Type 4 driver (fully Java driver)

• Type-4 driver is also called native protocol driver. This


driver interact directly with database. It does not require
any native database library, that is why it is also known
as Thin Driver.

Advantages
• Does not require any native library and Middleware
server, so no client-side or server-side installation.
• It is fully written in Java language, hence they are
portable drivers.
Thin driver – Type 4 driver (fully
Java driver)

Disadvantage
•If the database varies, then the driver will vary
because it is database dependent.
JDBC Architecture
• The JDBC API supports both two-tier and three-tier processing
models for database access.
• In the two-tier model, a Java applet or application talks directly to
the data source. This requires a JDBC driver that can communicate
with the particular data source being accessed. A user's
commands are delivered to the database or other data source,
and the results of those statements are sent back to the user. The
data source may be located on another machine to which the user
is connected via a network. This is referred to as a client/server
configuration, with the user's machine as the client, and the
machine housing the data source as the server. The network can
be an intranet, which, for example, connects employees within a
corporation, or it can be the Internet.
JDBC Architecture
JDBC Architecture
• In the three-tier model, commands are sent to a "middle
tier" of services, which then sends the commands to the
data source. The data source processes the commands
and sends the results back to the middle tier, which
then sends them to the user. MIS directors find the
three-tier model very attractive because the middle tier
makes it possible to maintain control over access and
the kinds of updates that can be made to corporate
data. Another advantage is that it simplifies the
deployment of applications. Finally, in many cases, the
three-tier architecture can provide performance
advantages.
JDBC Architecture
JDBC Architecture
• Until recently, the middle tier has often been written in languages such as
C or C++, which offer fast performance. However, with the introduction of
optimizing compilers that translate Java bytecode into efficient machine-
specific code and technologies such as Enterprise JavaBeans™, the Java
platform is fast becoming the standard platform for middle-tier
development. This is a big plus, making it possible to take advantage of
Java's robustness, multithreading, and security features.

• With enterprises increasingly using the Java programming language for


writing server code, the JDBC API is being used more and more in the
middle tier of a three-tier architecture. Some of the features that make
JDBC a server technology are its support for connection pooling,
distributed transactions, and disconnected rowsets. The JDBC API is also
what allows access to a data source from a Java middle tier.
Interfaces of JDBC API

• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
Classes of JDBC API

• DriverManager:
• Description: This class manages the set of database drivers.
It is responsible for establishing connections between Java
applications and the database.
• Usage:
• Registering Drivers: Use DriverManager.registerDriver(Driver
driver) to register a driver.
• Establishing Connections: The method getConnection(String
url, String user, String password) is used to create a
connection to the database.
Classes of JDBC API
• Driver Discovery:
• When a connection is requested, DriverManager
automatically locates suitable drivers without requiring
explicit loading of driver classes in most cases
(especially since JDBC 4.0). This simplifies the process
for developers.
• Login Timeout Management:
• The DriverManager allows setting and retrieving the
maximum time a driver will wait while attempting to
connect to a database through methods like
setLoginTimeout(int seconds) and getLoginTimeout().
DriverManager in a Multithreaded
Environment
• Using the DriverManager class in a multi-threaded
environment presents several limitations and
challenges:
• Connection Sharing Issues: Single Thread Access: Most
JDBC drivers do not allow multiple threads to use the
same `Connection` object simultaneously. If one thread
is executing a query while another tries to access the
same connection, it can lead to confusion and errors. As
a result, only one thread can perform operations on a
connection at any given time, potentially causing
performance bottlenecks.
DriverManager in a Multithreaded
Environment
• Performance Bottlenecks:
• Blocking Behavior: When multiple threads attempt to use the same
connection, threads that arrive later must wait for the ongoing
operation to complete. This can significantly degrade performance,
especially in applications with high concurrency demands, such as
web servers handling multiple requests simultaneously.
• Synchronization Overhead:
• Increased Complexity: Managing access to a shared connection
requires careful synchronization, which can complicate code and
introduce potential for deadlocks or race conditions if not handled
properly. This adds overhead and complexity to the application
logic.
DriverManager in a Multithreaded
Environment
• Connection Pooling Requirement:
• Need for Connection Pools: To mitigate the limitations of DriverManager
in multi-threaded environments, developers often need to implement
connection pooling. This involves creating a pool of connections that can
be shared among threads, allowing each thread to obtain a connection
without waiting for others. However, implementing and managing a
connection pool adds additional complexity and resource overhead.
• Thread Safety Concerns:
• Driver Implementation Variability: While some JDBC drivers are designed
to be thread-safe, others may not be. This inconsistency means that
developers cannot assume that all drivers will handle concurrent access
safely, necessitating caution when designing multi-threaded
applications.
Result Sets and Cursors

• The rows that satisfy the conditions of a query are called the result set.
The number of rows returned in a result set can be zero, one, or many. A
user can access the data in a result set one row at a time, and a cursor
provides the means to do that. A cursor can be thought of as a pointer
into a file that contains the rows of the result set, and that pointer has
the ability to keep track of which row is currently being accessed. A
cursor allows a user to process each row of a result set from top to
bottom and consequently may be used for iterative processing. Most
DBMSs create a cursor automatically when a result set is generated.

• Earlier JDBC API versions added new capabilities for a result set's cursor,
allowing it to move both forward and backward and also allowing it to
move to a specified row or to a row whose position is relative to another
row.
ResultSet Interface

• The ResultSet interface provides methods for retrieving and


manipulating the results of executed queries, and ResultSet objects can
have different functionality and characteristics. These characteristics
are type, concurrency, and cursor holdability.

• ResultSet Types:
• The type of a ResultSet object determines the level of its functionality
in two areas: the ways in which the cursor can be manipulated, and
how concurrent changes made to the underlying data source are
reflected by the ResultSet object.

• The sensitivity of a ResultSet object is determined by one of three


different ResultSet types:
ResulSet Types
• TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves
forward only, from before the first row to after the last row. The rows contained
in the result set depend on how the underlying database generates the results.
That is, it contains the rows that satisfy the query at either the time the query
is executed or as the rows are retrieved.
• TYPE_SCROLL_INSENSITIVE: The result can be scrolled; its cursor can move
both forward and backward relative to the current position, and it can move to
an absolute position. The result set is insensitive to changes made to the
underlying data source while it is open. It contains the rows that satisfy the
query at either the time the query is executed or as the rows are retrieved.
• TYPE_SCROLL_SENSITIVE: The result can be scrolled; its cursor can move both
forward and backward relative to the current position, and it can move to an
absolute position. The result set reflects changes made to the underlying data
source while the result set remains open.
• The default ResultSet type is TYPE_FORWARD_ONLY.
ResultSet Concurrency
• The concurrency of a ResultSet object determines what level of update
functionality is supported.
• There are two concurrency levels:
• CONCUR_READ_ONLY: The ResultSet object cannot be updated using
the ResultSet interface.
• CONCUR_UPDATABLE: The ResultSet object can be updated using the
ResultSet interface.
• The default ResultSet concurrency is CONCUR_READ_ONLY.
• Not all databases and JDBC drivers support all ResultSet types and
concurrency. The method DatabaseMetaData.supportsResultSetType
and DatabaseMetaData.supportsResultSetConcurrency returns true if
the specified ResultSet type and specified concurrency level is
supported and false otherwise.
Retrieving Column Values from Rows
• The ResultSet interface declares getter methods for retrieving column values
from the current row. You can retrieve values using either the index number of
the column or the alias or name of the column. The column index is usually
more efficient. Columns are numbered from 1. For maximum portability, result
set columns within each row should be read in left-to-right order, and each
column should be read only once.

• Strings used as input to getter methods are case-insensitive. When a getter


method is called with a string and more than one column has the same alias or
name as the string, the value of the first matching column is returned. The
option to use a string as opposed to an integer is designed to be used when
column aliases and names are used in the SQL query that generated the result
set. For columns that are not explicitly named in the query it is best to use
column numbers. If column names are used, the developer should guarantee
that they uniquely refer to the intended columns by using column aliases.
Cursors

• We can access the data in a ResultSet object through a


cursor, which points to one row in the ResultSet object.
However, when a ResultSet object is first created, the
cursor is positioned before the first row.
• There are other methods available to move the cursor:
• next: Moves the cursor forward one row. Returns true if the
cursor is now positioned on a row and false if the cursor is
positioned after the last row.
• previous: Moves the cursor backward one row. Returns
true if the cursor is now positioned on a row and false if
the cursor is positioned before the first row.
Cursor
• first: Moves the cursor to the first row in the ResultSet object. Returns true if the
cursor is now positioned on the first row and false if the ResultSet object does not
contain any rows.
• last: Moves the cursor to the last row in the ResultSet object. Returns true if the
cursor is now positioned on the last row and false if the ResultSet object does not
contain any rows.
• beforeFirst: Positions the cursor at the start of the ResultSet object, before the
first row. If the ResultSet object does not contain any rows, this method has no
effect.
• afterLast: Positions the cursor at the end of the ResultSet object, after the last
row. If the ResultSet object does not contain any rows, this method has no effect.
• relative(int rows): Moves the cursor relative to its current position.
• absolute(int row): Positions the cursor on the row specified by the parameter row.
Updating Rows in ResultSet Objects
• We can create ResultSet objects that can be scrolled
(the cursor can move backwards or move to an absolute
position) and updated.
• The field ResultSet.TYPE_SCROLL_SENSITIVE creates a
ResultSet object whose cursor can move both forward
and backward relative to the current position and to an
absolute position. The field
ResultSet.CONCUR_UPDATABLE creates a ResultSet
object that can be updated.
CONCUR_UPDATABLE
• public void modifyPrices(float percentage) throws SQLException {
• try (Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)) {
• ResultSet rs = stmt.executeQuery("SELECT * FROM COFFEES");
• while(rs.next()) {
• float f = rs.getFloat("PRICE");
• rs.updateFloat("PRICE", f * percentage);
• rs.updateRow(); }
• } catch (SQLException e) {} }
• The method ResultSet.updateFloat updates the specified column (in this example,
PRICE with the specified float value in the row where the cursor is positioned).
ResultSet contains various updater methods that enable you to update column
values of various data types. However, none of these updater methods modifies
the database; you must call the method ResultSet.updateRow to update the
database.
• public void insertRow(String coffeeName, int supplierID, float price,
• int sales, int total) throws SQLException {
• try (Statement stmt =
• con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE))
• {
• ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
• uprs.moveToInsertRow();
• uprs.updateString("COF_NAME", coffeeName);
• uprs.updateInt("SUP_ID", supplierID);
• uprs.updateFloat("PRICE", price);
• uprs.updateInt("SALES", sales);
• uprs.updateInt("TOTAL", total);
• uprs.insertRow();
• uprs.beforeFirst();

• } catch (SQLException e) {
• JDBCTutorialUtilities.printSQLException(e);
• }
Types of Statements in JDBC
• The Statement interface in JDBC is used to create SQL
statements in Java and execute queries with the
database. There are different types of statements used
in JDBC:

• Statement
• PreparedStatement
• CallableStatement
Statement object
• A Statement object is used for general-purpose access to databases
and is useful for executing static SQL statements at runtime.
• Statement statement = connection.createStatement();
• The object used for executing a static SQL statement and returning
the results it produces.

• By default, only one ResultSet object per Statement object can be


open at the same time. Therefore, if the reading of one ResultSet
object is interleaved with the reading of another, each must have
been generated by different Statement objects. All execution
methods in the Statement interface implicitly close a current
ResultSet object of the statement if an open one exists.
PreparedStatement
• A PreparedStatement represents a precompiled SQL statement
that can be executed multiple times. It accepts parameterized
SQL queries, with ? as placeholders for parameters, which can be
set dynamically.
• String query = "INSERT INTO student(name, age) VALUES(?, ?)";
• PreparedStatement pstmt = con.prepareStatement(query);
• pstmt.setString(1,"Amit");
• ptstmt.setInt(2,20);
• the method prepareStatement will send the statement to the
database for precompilation.
• // where pstmt is an object name
CallableStatement
• A CallableStatement is used to execute stored procedures in the
database. Stored procedures are precompiled SQL statements
that can be called with parameters. They are useful for executing
complex operations that involve multiple SQL statements.
• CallableStatement cstmt = con.prepareCall("{call
ProcedureName(?, ?)}");
• {call ProcedureName(?, ?)}: Calls a stored procedure named
ProcedureName with placeholders ? for input parameters.
• Creates a CallableStatement object for calling database stored
procedures. The CallableStatement object provides methods for
setting up its IN and OUT parameters, and methods for executing
the call to a stored procedure.
executeQuery() Method
• ResultSet executeQuery(String sql)
• throws SQLException
• Executes the given SQL statement, which returns a single
ResultSet object.
• Note:This method cannot be called on a
PreparedStatement or CallableStatement.
• sql - an SQL statement to be sent to the database,
typically a static SQL SELECT statement
• a ResultSet object that contains the data produced by the
given query; never null
executeUpdate() Method
• int executeUpdate(String sql)
• throws SQLException
• Executes the given SQL statement, which may be an INSERT,
UPDATE, or DELETE statement or an SQL statement that
returns nothing, such as an SQL DDL statement.
• Note:This method cannot be called on a PreparedStatement
or CallableStatement.
• sql - an SQL Data Manipulation Language (DML) statement,
such as INSERT, UPDATE or DELETE; or an SQL statement
that returns nothing, such as a DDL statement.
execute() Method
• String query = "{call delete_all_rows_from_table(?)}";
• CallableStatement statement =
connection.prepareCall(query);
• statement.setString(1, "all");
• statement.execute();
• Note: if the procedure got some out parameters, you
would have to register the parameters.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy