0% found this document useful (0 votes)
57 views

JDBC Introduction: Nitin Gupta A-11 Saivatika Devpuri 9302545188 (Web Project Developer)

JDBC is a Java API that allows Java programs to execute SQL statements. There are four types of JDBC drivers: Type 1 uses JDBC-ODBC bridge; Type 2 is database-specific; Type 3 is 100% Java and server-based; Type 4 communicates directly with the database server using Java networking libraries. To use JDBC, a program first loads a JDBC driver, gets a connection, creates a statement, executes the SQL query, and processes the results.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

JDBC Introduction: Nitin Gupta A-11 Saivatika Devpuri 9302545188 (Web Project Developer)

JDBC is a Java API that allows Java programs to execute SQL statements. There are four types of JDBC drivers: Type 1 uses JDBC-ODBC bridge; Type 2 is database-specific; Type 3 is 100% Java and server-based; Type 4 communicates directly with the database server using Java networking libraries. To use JDBC, a program first loads a JDBC driver, gets a connection, creates a statement, executes the SQL query, and processes the results.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

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

Native-API, partly Java driver, also called Type 2.


The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls
i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below.
Example :-- oracle.jdbc.pool.OracleDataSource ,
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-
ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

JDBC-Net, pure Java driver, also called Type 3.


Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the
request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load
balancing, and advanced.system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take longer, since the data
comes through the backend server.
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)

Native-protocol, pure Java driver, also called Type 4.


The Type 4 uses java networking libraries to communicate directly with the database server.
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform
independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or
a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
JDBC Basics - Java Database Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the
java.sql package. import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.

Establish the connection

Define the SQL statement

Send the SQL statement

executeQuery() executeUpdate()
select insert,update,delete,create,alter, drop
alter create delete

1. Loading a database driver,


there are two ways to lode the driver
first: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
second: DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

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();

A statement object is used to send and execute SQL statements to a database.


NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)

Three kinds of Statements


Statement: Execute simple sql queries without parameters.
Statement createStatement ()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.

Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call
statements.
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Statement interface defines methods that are used to interact with database via the execution of SQL
statements. The Statement class has three methods for executing statements: executeQuery(),
executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For
statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create
a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.

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.

5. Close the Connection


when you are finished performing queries and processing results and should close the connection and
release the resource
getXXX():--We use the getXXX()method of the appropriate type to retrieve the value in each column. For
example rs.getInt(),rs.getString(),rs.getFloat() etc.
DatabaseMetadata:- public interface DatabaseMetaData give you Comprehensive information about the database as a
whole.
ResultSetMetaData :- public interface ResultSetMetaData that can be used to get information about the types and
properties of the columns in a ResultSet object.
When st.executeQuery(sqlQuery); or st.executeUpdate(sqlQry); is called by our java application the
following statement will be executed.
1. JDBC driver sends the sql statement to the database server.
2. The database server split the statement into multiple pieces(tokens) and analyze whether the
statement is valid or not .This is called parsing
3. If statement is valid then server execute the statement otherwise server throw SQLException.
Transactions
Disabling Auto-commit Mode:- When a connection is created, it is in auto-commit mode. This means that each
individual SQL statement is treated as a transaction and will be automatically committed right after it is executed.The way
to allow two or more statements to be grouped into a transaction is to disable auto-commit mode.
con.setAutoCommit(false);//this is recommanded
Using Transactions to Preserve Data Integrity:-- Data integrity means some body modify the data in database but . At
the same time, the owner is executing a SELECT statement and getting modify rows. To avoid conflicts during a
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)

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.

An example of a PreparedStatement object is

PreparedStatement pstmt = con.prepareStatement(”update Orders set pname = ? where Prod_Id = ?”);


pstmt.setInt(2, 100);
pstmt.setString(1, “Bob”);
pstmt.executeUpdate();

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.

Create the Command with Placeholders:

// Stored procedure call


String command = "{call PROCEDURENAME(?,?,?,?)}"; // 4 placeholders

// Stored function call


String command = "{? = call FUNCTIONNAME(?,?,?,?)}"; // 4 placeholders + 1 return value

Create a Callable Statement Object:

CallableStatement cstmt = con.prepareCall (command);

(Throws a SQLException error.)

Register the IN and OUT Placeholders:

// Assign IN parameters (use positional placement)


cstmt.setInt(1, 50); // first placeholder has an integer value of 50
cstmt.setString(2, "Smith"); // second placeholder has a string value of "Smith"
cstmt.registerOutParameter(3, Types.NUMERIC); // NUMERIC is preferred over INTEGER with some databases
cstmt.registerOutParameter(4, Types.VARCHAR); // fourth placeholder is an OUT field of type VARCHAR.

(Throws a SQLException error.)


* Note: INOUT fields may be registered using the setXXX() and registerOutParameter() methods for the same
placeholder position. Array parameters (i.e. PL/SQL Tables) used in Oracle stored procedure and function calls are not
supported by the JDBC.
Execute the Procedure or Function Call:
cstmt.execute();
(Throws a SQLException error.)
Process the OUT Placeholders:
/** Use proper getXXX() method based on parameter data type.
* Placeholder 3 will receive a NUMERIC value as a BigDecimal object with 0 decimal places.
* Placeholder 4 will receive a VARCHAR value as a String object.
*/
BigDecimal num = cstmt.getBigDecimal(3,0);
String str = cstmt.getString(4);

(Throws a SQLException error.)

Close the CallableStatement Object:

// Close the call object after update is complete


cstmt.close();
NITIN GUPTA A-11 SAIVATIKA DEVPURI 9302545188(WEB PROJECT DEVELOPER)

New Features in the JDBC 2.0 API


 Scroll forward and backward in a result set or move to a specific row.
 Make updates to database tables, using methods in the Java programming language instead of using SQL commands.
 Send multiple SQL statements to the database as a unit, or a batch.
Moving the Cursor in Scrollable Result Sets
JDBC 2.0 API is the ability to move a result set's cursor first,last,backward as well as forward. There are also methods
that let you move the cursor to a particular row and check the position of the cursor. Scrollable result sets make it possible
to create a GUI (graphical user interface) tool for browsing result sets, which will probably be one of the main uses for
this feature. Another use is moving to a row in order to update it.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

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)

2. Invoke the commit method to commit the changes.


To make batch updates using a single statement with several sets of input parameters, follow these basic steps:
1. Disable AutoCommit for the Connection object.
2. Invoke the prepareStatement method to create a PreparedStatement object for the SQL statement with input
parameters.
3. For each set of input parameter values:
1. Execute setXXX methods to assign values to the input parameters.
2. Invoke the addBatch method to add the set of input parameters to the batch.
4. Invoke the executeBatch method to execute the statements with all sets of parameters.
5. Check for errors. If no errors occurred:
1. Get the number of rows that were updated by each execution of the SQL statement from the array that the
executeBatch invocation returns.
2. Invoke the commit method to commit the changes.
Before carrying out a batch update, it is important to disable the auto-commit mode by calling setAutoCommit(false). This
way, you will be able to rollback the batch transaction in case one of the updates fail for any reason. When the Statement
object is created, it is automatically associated a "command list", which is initially empty. We then add our SQL update
statements to this command list, by making successive calls to the addBatch() method. On calling executeBatch(), the
entire command list is sent over to the database, and are then executed in the order they were added to the list. If all the
commands in the list are executed successfully, their corresponding update counts are returned as an array of integers.
Please note that you always have to clear the existing batch by calling clearBatch() before creating a new one.

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

You might also like