JDBC Introduction: Nitin Gupta A-11 Saivatika Devpuri 9302545188 (Web Project Developer)
JDBC Introduction: Nitin Gupta A-11 Saivatika Devpuri 9302545188 (Web Project Developer)
JDBC Introduction
JDBC is not a software product. The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing
database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to
almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It is
an API which defines some standard interfaces and classes for writing database application in java. Java.sql.*; and
javax.sql.*; packages provide the necessary library support for java application. In order to establish the connection the
name of the driver class and jdbc url is required. Driver class name and jdbc url is different for different database server
and different type of driver. For example
OracleXE use ojdbc14.jar , Oracle9i use classes12.jar, Mysql use mysql-connector-java-3.0.8-stable-bin.jar , SQL
Server2000 use mssqlserver.jar file to establish the connection.Even though all jar file is different but they follow the
standard API means all classes, Interface and method are same for all database server.
JDBC Architecture
Figure 1: Two-tier Architecture for Data Access. Figure 2: Three-tier Architecture for Data Access.
JDBC Driver
JDBC Drivers are client-side adaptors (they are installed on the client machine, not on the server) that convert requests
from Java programs to a protocol that the DBMS can understand.
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.DriverManager's responsibility
to load all the drivers found in the system property jdbc. Drivers.
Types of JDBC drivers
There are four types of JDBC drivers known as:
JDBC-ODBC bridge plus ODBC driver, also called Type 1.
Native-API, partly Java driver, also called Type 2.
JDBC-Net, pure Java driver, also called Type 3.
Native-protocol, pure Java driver, also called Type 4.
JDBC-ODBC bridge plus ODBC driver( Type 1):--
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API.
The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this
applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)
Type 1: JDBC-ODBC Type 2: Native api/ Partly Type 3: All Java/ Net- Type 4: Native-
Bridge Java Driver Protocol Driver protocol/all-Java driver
executeQuery() executeUpdate()
select insert,update,delete,create,alter, drop
alter create delete
Class.forName is recommanded because Class.forName () is a static method and its load when that
class is loaded there is no need for driver object.When we are use DriverManager then first register the
driver and make new object for the driver
2. Creating a oracle jdbc Connection,
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.
DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the
JDBC drivers that are installed on the system. Its getConnection() method is used to establish a
connection to a database.
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
3. Creating a jdbc Statement object,
Once a connection is obtained we can interact with the database. Connection interface defines methods
for interacting with the database via the established connection. To execute SQL statements, you need to
instantiate a Statement object from your connection object by using the createStatement() method.
Statement statement = dbConnection.createStatement();
ResultSet provides access to a table of data generated by executing a Statement. The table rows are
retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next()
method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
transaction, a DBMS will use locks. In java we are use transaction isolation level is
TRANSACTION_READ_COMMITTED , which will not allow a value to be accessed until after it has been committed.
con.setTransactionIsolation(TRANSACTION_READ_COMMITTED);
Prepared statements
Prepared statements are pre-compiled SQL statements. Precompiled SQL is useful if the same SQL is to be executed
repeatedly, for example, in a loop. Prepared statements in java only save you time if you expect to execute the same SQL
over again. Every java sql prepared statement is compiled at some point. To use a java preparedstatements, you must first
create a object by calling the Connection. PrepareStatement () method. JDBC PreparedStatements are useful especially in
situations where you can use a for loop or while loop to set a parameter to a succession of values. If you want to execute a
Statement object many times, it normally reduces execution time to use a PreparedStatement object instead.
You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute
a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class.
There is a setXXX method for each primitive type declared in the Java programming language.
Suppose you want to insert record throw st.executeUpdate() is called reputedly 200 times. The jdbc driver sends the sql
statement for 200 time to the server, the server perform 200 times parsing ,validate and carries out the execution for 200
times. We can improve the performance this type of application using Prepared Statements instead of using statement
object. As a part of sql statement we must use “?” symbol without providing values the “?” are called parameters/place
holder. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it
with different values each time you execute it. PreparedStatement object is a precompiled compile statement. This means
that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without
having to compile it first.
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)
Stored Procedures
CallableStatement is an extension of the PreparedStatement interface. Parameters passed to and from the stored procedure
are identified using ? Placeholder symbols. These placeholders must be registered as IN our OUT data elements, using
data types from the Types class.
A stored procedure is a program that is kept and executed within a database server. You call the procedure from a Java
class using a special syntax .When you call it, the name of the procedure and the parameters you specify are sent over the
JDBC connection to the DBMS, which executes the procedure and returns the results (if any) back over the connection.
Difference between procedure and function:--procedure can read in a list of values but won't directly return any
values(it may indirectly return values). A function can also read a list of values but will explicitly return a single result.
The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable:
CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you
must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters
are of type int , the compiler will not complain if you switch the order.
There is two type of SCROLLABLE ResultSet.
1. SCROLL_SENSITIVE RS:-we can use the method refreshRow() and get the fresh data (if the data is updated, it will
get the updated data. )
2. SCROLL_INSENSITIVE RS:-- ResultSet is not sensitive to the changes made by another client. i.e, we cannot get the
fresh data using refreshRow().
We cannot insert, update, delete the data using readonly ResultSet.( ResultSet.CONCUR_READ_ONLY)
We can update the rows of resultSet using updatable ResultSet(ResultSet.CONCUR_UPDATABLE) we can use
updateXXX() method is used the data will be modified in the ResultSet. To apply this changes using updateRow().
Specifying Result Set Scrollability and Updatability
ResultSet.TYPE_FORWARD_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_SCROLL_SENSITIVE
ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
Batch Updates
A batch update is a set of multiple update statements that is submitted to the database for processing as a batch. Sending
multiple update statements to the database together as a unit can, in some situations, be much more efficient than sending
each update statement separately. This ability to send updates as a unit, referred to as the batch update facility, is one of
the features provided with the JDBC 2.0 API
Use the following Statement methods for creating, executing, and removing a batch of SQL updates:
* addBatch
* executeBatch
* clearBatch
Use the following PreparedStatement and CallableStatement method for creating a batch of parameters so that a single
statement can be executed multiple times in a batch, with a different set of parameters for each execution.
* addBatch
To make batch updates using several statements with no input parameters, follow these basic steps:
1. Disable AutoCommit for the Connection object.
2. Invoke the createStatement method to create a Statement object.
3. For each SQL statement that you want to execute in the batch, invoke the addBatch method.
4. Invoke the executeBatch method to execute the batch of statements.
5. Check for errors. If no errors occurred:
1. Get the number of rows that were affect by each SQL statement from the array that the executeBatch invocation
returns. This number does not include rows that were affected by triggers or by referential integrity enforcement.
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)
If any of the updates fail to execute within the database, a BatchUpdateException is thrown in response to it. In case there
is a problem in returning the update counts of each SQL statement, a SQLException will be thrown to indicate the error.
Example of a batch update: In the following code fragment, two sets of parameters are batched. An UPDATE statement
that takes two input parameters is then executed twice, once with each set of parameters. The numbers to the right of
selected statements correspond to the previously-described steps.
SQL3 Datatypes
SQL3 type getXXX method setXXX method updateXXX method
BLOB getBlob setBlob updateBlob
CLOB getClob setClob updateClob
ARRAY getArray setArray updateArray
Structured type getObject setObject updateObject
REF (structured type) getRef setRef updateRef
Standard Extension Features
The package javax.sql, a standard extension to the Java programming language, provides these features:
Rowsets
A rowset encapsulates a set of rows from a result set and may maintain an open database connection or be
disconnected from the data source. A rowset is a JavaBeans tm component; it can be created at design time and used in
conjunction with other JavaBeans components in a visual JavaBeans builder tool to construct an application.
JNDI tm for Naming Databases
The Java tm Naming and Directory Interface tm (JNDI) makes it possible to connect to a database using a logical
name instead of having to hard code a particular database and driver.
Connection Pooling
A connection pool is a cache of open connections that can be used and reused, thus cutting down on the overhead of
creating and destroying database connections.
Distributed Transaction Support
Support for distributed transactions allows a JDBC driver to support the standard two-phase commit protocol used by
the Java Transaction API (JTA). This feature facilitates using JDBC functionality in Enterprise JavaBeans components