jdbc document

42
CONTENTS 1.Abstract 2.Introduction 3.Literature Survey 4.Functionality 5.Advantages 6.Disadvantages 7.Further Enhancements 8.Design Implementation 9.Reference 10.Conclusion 1

Transcript of jdbc document

Page 1: jdbc document

CONTENTS

1.Abstract 2.Introduction 3.Literature Survey 4.Functionality

5.Advantages

6.Disadvantages

7.Further Enhancements

8.Design Implementation

9.Reference

10.Conclusion

1

Page 2: jdbc document

Abstract:

JDBCT is a JavaT API for executing SQL statements. (As a point of interest, JDBC is a trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for "Java Database Connectivity".) It consists of a set of classes and interfaces written in the Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API.

Using JDBC, it is easy to send SQL statements to virtually any relational database. In other words, with the JDBC API, it isn't necessary to write one program to access a Sybase database, another program to access an Oracle database, another program to access an Informix database, and so on. One can write a single program using the JDBC API, and the program will be able to send SQL statements to the appropriate database. And, with an application written in the Java programming language, one also doesn't have to worry about writing different applications to run on different platforms. The combination of Java and JDBC lets a programmer write it once and run it anywhere.

JDBC is a Java-based data access technology (Java Standard Edition platform) from Oracle Corporation. This technology is an API for the java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the JVM host environment.Java Database Connectivity (JDBC) API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases – SQL databases and other tabular data sources, such as spreadsheets or flat files. The JDBC API provides a call-level API for SQL-based database access.

2

Page 3: jdbc document

Introduction of Java Database Connectivity

JDBC - Java Database Connectivity.

JDBC provides API or Protocol to interact with different databases.

With the help of JDBC driver we can connect with different types of databases.

Driver is must needed for connection establishment with any database.

A driver works as an interface between the client and a database server.

JDBC have so many classes and interfaces that allow a java application to send request made by user to any specific DBMS(Data Base Management System).

JDBC supports a wide level of portability.

JDBC provides interfaces that are compatible with java application.

components and specification of JDBC:

3

Page 4: jdbc document

Components of JDBC:

JDBC has four main components as under and with the help of these components java application can connect with database.

The JDBC API - it provides various methods and interfaces for easy communication with database.

The JDBC DriverManager - it loads database specific drivers in an application to establish connection with database.

The JDBC test suite - it will be used to test an operation being performed by JDBC drivers.

The JDBC-ODBC bridge - it connects database drivers to the database.

JDBC Specification:

Different version of JDBC has different specification as under.

JDBC 1.0 - it provides basic functionality of JDBC

JDBC 2.0 - it provides JDBC API(JDBC 2.0 Core API and JDBC 2.0 Optional Package API).

JDBC 3.0 - it provides classes and interfaces in two packages(java.sql and javax.sql).

JDBC 4.0 - it provides so many extra features like

Auto loading of the driver interface.

Connection management

ROWID data type support.

Enhanced support for large object like BLOB(Binary Large Object) and CLOB(Character Large Object). 

-----What Does JDBC Do?

Simply put, JDBC makes it possible to do three things:

1. establish a connection with a database2. send SQL statements3. process the results.

4

Page 5: jdbc document

JavaSoft provides three JDBC product components as part of the Java Developer's Kit (JDK):

1. . the JDBC driver manager,2. . the JDBC driver test suite, and3. . the JDBC-ODBC bridge.

The JDBC driver manager is the backbone of the JDB architecture. It actually is quite small and simple; its primary function is to connect Java applications to the correct JDBC driver and then get out of the way

JDBC Architecture:

As we all know now that driver is required to communicate with database.

JDBC API provides classes and interfaces to handle request made by user and response made by database.

Some of the important JDBC API are as under.

DriverManager

Driver

Connection

Statement

PreparedStatement

CallableStatement

ResultSet

DatabaseMetaData

ResultSetMetaData

Here The DriverManager plays an important role in JDBC architecture.

It uses some database specific drivers to communicate our J2EE application to database.

5

Page 6: jdbc document

As per the diagram first of all we have to program our application with JDBC API.

With the help of DriverManager class than we connect to a specific database with the help of spcific database driver.

Java drivers require some library to communicate with the database.

6

Page 7: jdbc document

We have four different types of java drivers.

We will learn all that four drivers with architecture in next chapter.

Some drivers are pure java drivers and some are partial.

So with this kind of JDBC architecture we can communicate with specific database.

----JDBC Drivers:

JDBC Driver Types:

There are four categories of drivers by which developer can apply a connection between Client (The JAVA application or an applet) to a DBMS.

(1)   Type 1 Driver : JDBC-ODBC Bridge.

(2)   Type 2 Driver : Native-API Driver (Partly Java driver).

(3)   Type 3 Driver : Network-Protocol Driver (Pure Java driver for database Middleware).

(4)   Type 4 Driver : Native-Protocol Driver (Pure Java driver directly connected to database).

(1) Type 1 Driver: JDBC-ODBC Bridge  :-

The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.

SunprovidesDBC-ODBCBridgedriverby “sun.jdbc.odbc.JdbcOdbcDriver”.

The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC driver.

Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on Microsoft platform.

For type-1 we create the DSN name.

Steps for DSN:

7

Page 8: jdbc document

1. Start2. Control panel

3. Administrator tools

4. Data source odbc

5. System dsn

6. Add

7. Microsoft oracle for odbc

8. Finish

9. ora

The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a particular database.

The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC driver.

Java DB is Oracle's supported distribution of the open source Apache Derby database. Its ease of use, standards compliance, full feature set, and small footprint make it the ideal database for Java developers. Java DB is written in the Java programming language, providing "write once, run anywhere" portability. It can be embedded in Java applications, requiring zero administration by the developer or user. It can also be used in client server mode. Java DB is fully transactional and provides a standard SQL interface.

The JDBC driver manager is the backbone of the JDB architecture. It actually is quite small and simple; its primary function is to connect Java applications to the correct JDBC driver and then get out of the way

8

Page 9: jdbc document

Architecture Diagram:

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 1 Driver   →   ODBC Driver   → Database library APIs → Database

Advantage:

(1)   Connect to almost any database on any system, for which ODBC driver is installed.

(2)   It’s an easy for installation as well as easy(simplest) to use as compare the all other driver.

Disadvantage:

(1)   The ODBC Driver needs to be installed on the client machine.

9

Page 10: jdbc document

(2)   It’s a not a purely platform independent because its use ODBC which is depends on native libraries of the operating system on client machine.

(3) Not suitable for applets because the ODBC driver needs to be installed on the client machine.

(2) Type 2 Driver: Native-API Driver (Partly Java driver) :-

The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database  so this driver is also known as a Native-API driver.

Architecture Diagram :

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 2 Driver   →  Vendor Client Database library APIs → Database

10

Page 11: jdbc document

Advantage:

(1)   There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).

Disadvantage:

(1)   On the client machine require the extra installation because this driver uses the vendor client libraries.

(2)   The Client side software needed so cannot use such type of driver in the web-based application.

(3)   Not all databases have the client side library.

(4)   This driver supports all JAVA applications except applets.

(3) Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware) :-

The JDBC type 3 driver uses the middle tier(application server) between the calling program and the database and this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be used for multiple databases also so it’s also known as a Network-Protocol driver as well as a JAVA driver for database middleware.

Architecture Diagram:

11

Page 12: jdbc document

 

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 3 Driver   →  Middleware (Server)→ any Database

Advantage:

(1) There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client.

(2) Type 3 driver can be used in any web application as well as on internet also because there is no any software require at client side.

(3) A single driver can handle any database at client side so there is no need a separate driver for each database.

(4) The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc.

Disadvantage:

(1) An Extra layer added, may be time consuming.

(2) At the middleware develop the database specific coding, may be increase complexity.

(4) Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to database) :-

The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written in JAVA because of that this is also known as the “direct to database Pure JAVA driver”.

If we are using type-4 driver in oracle then we need to add jar file to the class path because it was given by third party.

12

Page 13: jdbc document

Architecture Diagram:

 

 

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 4 Driver (Pure JAVA Driver)   → Database Server

13

Page 14: jdbc document

Advantage:

(1)   It’s a 100% pure JAVA Driver so it’s a platform independence.

(2)   No translation or middleware layers are used so consider as a faster than other drivers.

(3)   The all process of the application-to-database connection can manage by JVM so the debugging is also managed easily.

Disadvantage:

(1)There is a separate driver needed for each database at the client side.

(2) Drivers are Database dependent, as different database vendors use different network protocols.

JDBC APIs:

If any java application or an applet wants to connect with a database then there are various classes and interfaces available in java.sql package.

Depending on the requirements these classes and interfaces can be used.

Some of them are list out the below which are used to perform the various tasks with database as well as for connection.

Class or Interface Description

Java.sql.Connection Create a connection with specific database

Java.sql.DriverManagerThe task of DriverManager is to manage the database driver

Java.sql.StatementIt executes SQL statements for particular connection and retrieve the results

Java.sql.PreparedStatementIt allows the programmer to create prepared SQL statements

Java.sql.CallableStatement It executes stored procedures

14

Page 15: jdbc document

Java.sql.ResultSetThis interface provides methods to get result row by row generated by SELECT statements

The Connection interface:

The Connection interface used to connect java application with particular database.

After crating the connection with database we can execute SQL statements for that particular connection using object of Connection and retrieve the results.

The interface has few methods that makes changes to the database temporary or permanently.

The some methods are as given below.

Method Description

void close()This method frees an object of type Connection from database and other JDBC resources.

void commit()This method makes all the changes made since the last commit or rollback permanent. It throws SQLExeception.

Statement createStatement()This method creates an object of type Statement for sending SQL statements to the database. It throws SQLExeception.

boolean isClosed()Return true if the connection is close else return false.

CallableStatement prepareCall(String s)

This method creates an object of type CallableStatement  for calling the stored procedures from database. It throws SQLExeception.

15

Page 16: jdbc document

PreparedStatement prepareStatement(String s)

This method creates an  object  of type PrepareStatement for sending dynamic (with or without IN parameter) SQL statements to the database. It throws SQLExeception.

void rollback()This method undoes all changes made to the database.

Statement Interface:

The Statement interface is used for to execute a static query.

It’s a very simple and easy so it also calls a “Simple Statement”.

The statement interface has several methods for execute the SQL statements and also get the appropriate result as per the query sent to the database.

Some of the most common methods are as given below

Method Description

void close()This method frees an object of type Statement from database and other JDBC resources.

boolean execute(String s)This method executes the SQL statement specified by s. The getResultSet() method is used to retrieve the result.

ResultSet getResultet()This method retrieves the ResultSet that is generated by the execute() method.

ResultSet executeQuery(String s)This method is used to execute the SQL statement specified by s and returns the object of type ResultSet.

16

Page 17: jdbc document

int getMaxRows()This method returns the maximum number of rows those are generated by the executeQuery() method.

Int executeUpdate(String s)This method executes the SQL statement specified by s. The SQL statement may be a SQL insert, update and delete statement.

The Prepared Statement Interface:

The Prepared Statement interface is used to execute a dynamic query (parameterized SQL statement) with IN parameter.

IN Parameter:-

In some situation where we need to pass different values to an query then such values can be specified as a “?” in the query and the actual values can be passed using the setXXX() method at the time of execution.

Syntax :        

            setXXX(integer data ,XXX value);

Where XXX means a data type as per the value we want to pass in the query.

For example,

String query = "Select * from Data where ID = ? and Name = ? ";

PreparedStatement ps = con.prepareStatement(query);

              ps.setInt(1, 1);   

              ps.setString(2, "Ashutosh Abhangi");

The Prepared statement interface has several methods to execute the parameterized SQL statements and retrieve appropriate result as per the query sent to the database.

Some of the most common methods are as given below

17

Page 18: jdbc document

Method Description

void close()This method frees an object of type Prepared Statement from database and other JDBC resources.

boolean execute()

This method executes the dynamic query in the object of type Prepared Statement.The getResult() method is used to retrieve the result.

ResultSet executeQuery()

This method is used to execute the dynamic query in the object of type Prepared Statement and returns the object of type ResultSet.

Int executeUpdate()

This method executes the SQL statement in the object of type Prepared Statement. The SQL statement may be a SQL insert, update and delete statement.

ResultSetMetaData getMetaData()

The ResultSetMetaData means a deta about the data of ResultSet.This method retrieves an object of type ResultSetMetaData that contains information about the columns of the ResultSet object that will be return when a query is execute.

int getMaxRows()This method returns the maximum number of rows those are generated by the executeQuery() method.

-

18

Page 19: jdbc document

Literature Survey

Sun Microsystems released JDBC as part of JDK1.1 on February 19, 1997.It has since

formed part of the Java Standard Edition.The JDBC classes are contained in the Java

package java.sql and javax.sql.

Starting with version 3.1, JDBC has been developed under the Java Community Process.

JSR 54 specifies JDBC 3.0 (included in J2SE 1.4), JSR 114 specifies the JDBC Rowset

additions, and JSR 221 is the specification of JDBC 4.0 (included in Java SE 6).The latest

version, JDBC 4.1, is specified by a maintenance release of JSR 221] and is included in

Java SE 7.

We can store our data permanently by using file concept.

If we are using file concept we have some drawbacks.

1. If we want to use file concept we need to know IO package

2. It can store small amount of data,insering deleting updating in files it takes more

time.

3. It doesn’t support query language.

4. To overcome all those problems we go for database softwares.

In database s/w the data will be stored permanently.It supports query lang and takes less time for insertion,deletion,updation,retrieve.Some of the database s/w are

1. Oracle2. Mysql3. Sqlserver4. Db2.

Now by using our javacode if we want to connect to database we are considered the jdbc.

The JDBC API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC API provides a call-level API for SQL-based database access. JDBC technology allows you to use the Java programming language to exploit "Write Once, Run Anywhere" capabilities for applications that require access to enterprise data. 

19

Page 20: jdbc document

Functionality

JDBC allows multiple implementations to exist and be used by the same application. The

API provides a mechanism for dynamically loading the correct Java packages and

registering them with the JDBC Driver Manager. The Driver Manager is used as a

connection factory for creating JDBC connections.

JDBC connections support creating and executing statements. These may be update

statements such as SQL's CREATE, INSERT, UPDATE and DELETE, or they may be

query statements such as SELECT. Additionally, stored procedures may be invoked

through a JDBC connection. JDBC represents statements using one of the following

classes:

Statement – the statement is sent to the database server each and every time.

PreparedStatement – the statement is cached and then the execution path is pre-

determined on the database server allowing it to be executed multiple times in an

efficient manner.

CallableStatement  – used for executing stored procedures on the database.

Update statements such as INSERT, UPDATE and DELETE return an update count that

indicates how many rows  were affected in the database. These statements do not return

any other information.

Query statements return a JDBC row result set. The row result set is used to walk over

the result set. Individual columns in a row are retrieved either by name or by column

number. There may be any number of rows in the result set. The row result set has

metadata that describes the names of the columns and their types.

There is an extension to the basic JDBC API in the javax.sql

JDBC connections are often managed via a connection pool  rather than obtained directly

from the driver.

The method Class.forName(String) is used to load the JDBC driver class. The line below

causes the JDBC driver from some jdbc vendor to be loaded into the application. (Some

JVMs also require the class to be instantiated with .newInstance().)

Class.forName( "com.somejdbcvendor.TheirJdbcDriver" );

20

Page 21: jdbc document

In JDBC 4.0, it is no longer necessary to explicitly load JDBC drivers

using Class.forName(). See JDBC 4.0 Enhancements in Java SE 6.

When a Driver class is loaded, it creates an instance of itself and registers it with

the DriverManager. This can be done by including the needed code in the driver

class's static block. E.g., DriverManager.registerDriver(Driver driver)

Now when a connection is needed, one of the DriverManager.getConnection() methods is

used to create a JDBC connection.

Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" );try { /* you use the connection here */} finally { //It's important to close the connection when you are done with it try { conn.close(); } catch (Throwable ignore) { /* Propagate the original exceptioninstead of this one that you may want just logged */ }}

Using Java's try-with-resources statement will make the above code cleaner:

try (Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ) ) { /* you use the connection here */} // the VM will take care of closing the connection

The URL used is dependent upon the particular JDBC driver. It will always begin with

the "jdbc:" protocol, but the rest is up to the particular vendor. Once a connection is

established, a statement can be created.

try (Statement stmt = conn.createStatement()) { stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );}

Note that Connections, Statements, and ResultSets often tie up operating

system resources such as sockets or file descriptors. In the case of Connections to remote

database servers, further resources are tied up on the server, e.g., cursors for currently

open ResultSets. It is vital to close() any JDBC object as soon as it has played its

part; garbage collection should not be relied upon. Forgetting toclose() things properly

21

Page 22: jdbc document

results in spurious errors and misbehaviour. The above try-with-resources construct is a

recommended[by whom?]code pattern to use with JDBC objects.

Data is retrieved from the database using a database query mechanism. The example

below shows creating a statement and executing a query.

try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" )) { while ( rs.next() ) { int numColumns = rs.getMetaData().getColumnCount(); for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. // Also there are many methods on the result set to return // the column as a particular type. Refer to the Sun documentation // for the list of valid conversions. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } }}

Typically, however, it would be rare for a seasoned Java programmer to code in such a

fashion. The usual practice would be to abstract the database logic into an entirely

different class and to pass preprocessed strings (perhaps derived themselves from a

further abstracted class) containing SQL statements and the connection to the required

methods. Abstracting the data model from the application code makes it more likely that

changes to the application and data model can be made independently.

An example of a PreparedStatement query, using conn and class from first example.

try (PreparedStatement ps = conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" )){ // In the SQL statement being prepared, each question mark is a placeholder // that must be replaced with a value you provide through a "set" method invocation. // The following two method calls replace the two placeholders; the first is // replaced by a string value, and the second by an integer value. ps.setString(1, "Poor Yorick"); ps.setInt(2, 8008); // The ResultSet, rs, conveys the result of executing the SQL statement. // Each time you call rs.next(), an internal row pointer, or cursor, // is advanced to the next row of the result. The cursor initially is // positioned before the first row.

22

Page 23: jdbc document

try (ResultSet rs = ps.executeQuery()) { while ( rs.next() ) { int numColumns = rs.getMetaData().getColumnCount(); for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. // Also there are many methods on the result set to return // the column as a particular type. Refer to the Sun documentation // for the list of valid conversions. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } // for } // while } // try} // try

If a database operation fails, JDBC raises an SQLException. There is typically very little

one can do to recover from such an error, apart from logging it with as much detail as

possible. It is recommended that the SQLException be translated into an application

domain exception (an unchecked one) that eventually results in a transaction rollback and

a notification to the user.

An example of a   database transaction :

boolean autoCommitDefault = conn.getAutoCommit();try { conn.setAutoCommit(false); /* You execute statements against conn here transactionally */ conn.commit();} catch (Throwable e) { try { conn.rollback(); } catch (Throwable ignore) {} throw e;} finally { try { conn.setAutoCommit(autoCommitDefault); } catch (Throwable ignore) {}}

23

Page 24: jdbc document

JDBC example with access:

To connect java application to access database we must have at least one database created in access.

Steps to create a database in MS-Access:

(1) Open Microsoft Office Access.

(2) Click on Blank Database.

(3) Type an appropriate name of database in File Name: box for example, HOD_DATA and click on Create Button.

(4) Create appropriate field name in table and value as per the field.

EX.:

The following was the example showing in ms access.

24

Page 25: jdbc document

(5) Right click on Table1 and select Save. Type the name of Table for example, DATA and click on OK button.

(6) Close the Table by right clicking on DATA and select Close. and Exit from Database

(7) Move this database to the appropriate drive where you want.

Now lets create TYPE 1 driver program for JDBC with access.

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; public class Type_One { public static void main(String[] args) {

25

Page 26: jdbc document

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver Connection con = DriverManager.getConnection("jdbc:odbc:HOD_DATA"); //Create Connection with Data Source Name : HOD_DATA Statement s = con.createStatement(); // Create Statement String query = "select * from Data"; // Create Query s.execute(query); // Execute Query ResultSet rs = s.getResultSet(); //return the data from Statement into ResultSet while(rs.next()) // Retrieve data from ResultSet { System.out.print("Serial number : "+rs.getString(1)); //1st column of Table from database System.out.print(" , Name : "+rs.getString(2)); //2nd column of Table System.out.print(" , City : "+rs.getString(3)); //3rd column of Table System.out.println(" and Age : "+rs.getString(4)); //4th column of Table } s.close(); con.close(); } catch (Exception e) { System.out.println("Exception : "+e); } }}Output:

Serial number : 1 , Name : Ashutosh Abhangi , City : Dhoraji and Age : 27

Serial number : 2 , Name : Kamal Kotecha , City : Junagadh and Age : 24

Example:

Question: inserting the values in to the database(oracle) using type-1 driver

import java.sql.*;

class Oracle3

{

26

Page 27: jdbc document

public static void main(String args[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection cn=DriverManager.getConnection("jdbc:odbc:ora","yamuna","sarasa");

System.out.println("established connection");

Statement stmt=cn.createStatement();

int id=10;

String s1="ramesh";

String s2="hyd";

String qry="insert in to employes values("+id+",'"+s1+"','"+s2+"')";

int i=stmt.executeUpdate(qry);

if(i>0)

{

System.out.println("inserted");

}

stmt.close();

cn.close();

}

catch(Exception e)

{

System.out.println(e);

}

27

Page 28: jdbc document

}

}

To execute a query, call an execute method from Statement such as the following:

execute: Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or

more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet.

executeQuery: Returns one ResultSet object. executeUpdate: Returns an integer representing the number of rows affected

by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATESQL statements.

Jdbc with Servlets and jsp’s

Java Servlets, or simply servlets are a set of Java classes that can be used and extended

for Web server-side programming provided the Web server supports Java servlets.

Basically, the programmer specifies which servlet is to be used to process which request

or which type of requests from client. Thus, when a request is received by the Web

server, the Web server finds the proper servlet for the request. For example, in an HTML

form,  its action clause can explicity specify which servlet be invoked to process the data

submitted through the form.  

JDBC is an application programming interface (JDBC API) that defines a set of standard

operations for interacting with relational database management systems (DBMSs). The

DBMSs may be located on a remote machine connected to the Internet. In order to access

28

Page 29: jdbc document

a database under a specific DBMS, for example, PostgreSQL, one must have a driver for

that DBMS and the driver must implement JDBC API. JDBC is a trademark name and

not an acronym. 

With HTML, Servlets, JDBC, and DBMS, we can easily build Web-based three-tier

systems -- client, Web server, and database server. HTML is used to design the client-

side interface that is to be executed on a Web browser such as Netscape and Internet

Explore. Servlets can be employed to do server-side programming and JDBC can be used

to interact with a database(s) for the requests from clients. The database(s) may be

located on a remote database server.

Advantages

1) Can read any database if proper drivers are installed.

                    2) Creates XML structure of data from database

                        automatically

                    3) No content conversion required

                    4) Query and Stored procedure supported.

                    5) Can be used for both Synchronus and Asynchronous

                        processing.

                    6) Supports modules

Disadvantages :

1) Correct drivers need to be deployed for each type

                            of database              

                  2) Cannot update or insert multiple tables with

                              sequence. ( Sequence is always randomn)

29

Page 30: jdbc document

Further Enhancement

Enhanced Broker Cluster Properties

Enhanced broker clusters, which share a JDBC-based data store, require more configuration than do conventional broker clusters. In addition to the properties listed in Cluster Connection Service Properties , the following categories of properties are used to configure an enhanced cluster:

Enhanced Clusters: General Configuration Properties Enhanced Clusters: JDBC Configuration Properties

Enhanced Clusters: Failure Detection Properties

Enhanced Clusters: JDBC Configuration Properties

The persistent data store for an enhanced cluster is maintained on a highly-available JDBC database.

The highly-availabile database may be Sun’s MySQL Cluster Edition or High Availability Session Store (HADB), or it may be an open-source or third-party product such as Oracle Corporation’s Real Application Clusters (RAC). As described in JDBC-Based Persistence Properties theimq.persist.jdbc.dbVendor  broker property specifies the name of the database vendor, and all of the remaining JDBC-related properties are qualified with this vendor name.

The JDBC-related properties are discussed under JDBC-Based Persistence Properties and summarized in Table 17–7. See the example configurations for MySQL and HADB in Example 8–1 and Example 8–2, respectively.

When using HADB in a Sun Java Application Server environment, if the integration between Message Queue and Application Server is local (that is, there is a one-to-one relationship between Application Server instances and Message Queue brokers), the Application Server will automatically propagate HADB-related properties to each broker in the cluster. However, if the integration is remote (a single Application Server instance using an externally configured broker cluster), then it is your responsibility to configure the needed HADB properties explicitly.

30

Page 31: jdbc document

JDBC driver enhancements

|Many new features and enhancements have been made to the JDBC drivers in |DB2(R) Version 8. Among these changes, the biggest change is a new|JDBC driver architecture known as the IBM(R) DB2 JDBC Universal |Driver. The Universal Driver is an architecture-neutral JDBC driver for|distributed and local DB2 access. The Universal Driver architecture is |independent of any particular JDBC driver-type connectivity or target |platform, which allows for both Type 4 and Type 2 connectivity in a single |driver instance to DB2 platforms. In addition, platform specifics are |abstracted to the lowest layers, so that driver differences among the various |DB2 platforms are minimized. The initial 1.0 release of the |Universal JDBC Driver supports only Type 4 connectitivity, which is based on |an open distributed protocol (known as Distributed Relational Database |Architecture, or DRDA) for cross-platform access to DB2.

|In DB2 Version 8:|

|

1. The new Type 4 JDBC driver is a two-tier pure Java(TM) JDBC driver that |allows a Java client to communicate directly with DB2 servers via the |DRDA(R) protocol. This driver is designed to replace the Type 3 |driver. You should migrate applets that use the Type 3 JDBC driver to |the Type 4 driver, in preparation for the end of Type 3 driver support

.

2. |DB2 provides a new SQLJ profile customizer that uses the Type 4 JDBC |driver.

3. |The JDBC drivers are available on 64-bit platforms.

4. |Better memory management improves the stability and performance of the |drivers.

5. |The JDBC 1.2 drivers are deprecated.

31

Page 32: jdbc document

|The new SQLJ translator supports the |java.sql.Blob and |java.sql.Clob types of JDBC 2.0, as well as |host variable expressions.

Design Implementation

Just as Java was designed to provide platform independence from hardware/software

platforms, so too JDBC has been designed to provide some degree of database

independence for developers. JDBC is designed to provide a database-neutral API for

accessing relational databases from different vendors. Just as a Java application does not

need to be aware of the operating system platform on which it is running, so too JDBC

has been designed so that the database application can use the same methods to access

data regardless of the underlying database product.

JDBC was developed to work with the most common type of database: the relational

database. This is not to say that JDBC cannot be used with another type of database. In

fact, there are JDBC drivers that allow the API to be used to connect to both high-end,

mainframe databases, which are not relational, and to access flat files and spreadsheets as

databases (which are definitely not relational). But the reality is that JDBC is most

commonly used with relational databases.

JDBC gives Java developers the power to database-enable virtually any application, on

virtually any platform, using virtually any database. In this book, leading JDBC expert

Art Taylor combines an expert JDBC tutorial and a definitive API reference that provides

thorough and detailed coverage of the new JDBC 3.0 standard. Taylor brings together

code examples, design patterns, and expert programming techniques for J2EE

programming. Code examples include Web development, GUI programming with Swing,

servlets, JSPs, EJBs, and RMI. Coverage includes:

Web database development capabilities leveraging JavaServer Pages(tm) and

servlets

Database access using Enterprise JavaBeans(tm) components

32

Page 33: jdbc document

Creating a GUI-based database browser using Swing

JDBC 3.0 support for scrollable cursors, batch updates, and connection pooling

DataSource lookup using JNDI,Using Blobs with JDBC

Dynamic SQL using JDBC database metadata

References:

1. "SUN SHIPS JDK 1.1 -- JAVABEANS INCLUDED" . www.sun.com. Sun

Microsystems. 1997-02-19. Archived from the original on 2008-02-10. Retrieved

2010-02-15. "February 19, 1997 - The JDK 1.1 [...] is now available [...]. This

release of the JDK includes: [...] Robust new features including JDBC[tm] for

database connectivity"

2.  JDBC API Specification Version: 4.0.

3.  SR-000221 JDBC API Specification 4.1 (Maintenance Release)

4.  http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/jdbc_41.html

5. "New Type 5 JDBC Driver - DataDirect Connect" .

6. Sualeh Fatehi. "SchemaCrawler". SourceForge.

External links

Java SE 7 This documentation has examples where the JDBC resources are not

closed appropriately (swallowing primary exceptions and being able to cause

NullPointerExceptions) and has code prone to SQL injection

java.sql API Javadoc documentation

javax.sql API Javadoc documentation

O/R Broker Scala JDBC framework

SqlTool Open source, command-line, generic JDBC client utility. Works with any

JDBC-supporting database.

JDBC URL Strings and related information of All Databases.

33

Page 34: jdbc document

Conclusion

Java, being robust, secure, easy to use, easy to understand, and automatically Downloadable on a network, is an excellent language basis for database applications. What is needed is a way for Java applications to talk to a variety of different databases. JDBC is the mechanism for doing this. JDBC extends what can be done in Java. For example, with Java and the JDBC API, it is possible to publish a web page containing an applet that uses information obtained from a remote database. Or an enterprise can use JDBC to connect all its employees (even if they are using a conglomeration of Windows, Macintosh, and UNIX machines) to one or more internal databases via an intranet.

With more and more programmers using the Java programming language, the need for easy database access from Java is continuing to grow. MIS managers like the combination of Java and JDBC because it makes disseminating information easy and economical. Businesses can continue to use their installed databases and access information easily even if it is stored on different database management systems. Development time for new applications is short. Installation and version control are greatly simplified. The JDBC driver manager is the backbone of the JDB architecture. It actually is quite small and simple; its primary function is to connect Java applications to the correct JDBC driver and then get out of the way

34