Anda di halaman 1dari 9

Technical Article

JDBC
Introduction:
In this we will discuss about JDBC 2.0. JDBC defines how a Java program can communicate with a
database. JDBC API provides two packages they are java.sql and javax.sql . By using JDBC API,
we can connect virtually any database, send SQL queries to the database and process the results.
Software and version used in this are:
• Jdk1.5.0
• Notepad / EditPlus

Definition:
JDBC 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 was first introduced in the Java 2 Platform, Standard Edition, version 1.1 (J2SE), together
with a reference implementation JDBC-to-ODBC bridge, enabling connections to any ODBC-
accessible data source in the JVM host environment.

JDBC Architecture:
Different database systems have surprisingly little in common: just a similar purpose and a mostly
compatible query language. Beyond that, every database has its own API that we must learn to
write programs that interact with the database. This has meant that writing code capable of
interfacing with databases from more than one vendor has been a daunting challenge. Cross-
database APIs exist, most notably Microsoft's ODBC API, but these tend to find themselves, at best,
limited to a particular platform.

JDBC is Sun's attempt to create a platform-neutral interface between databases and Java. With
JDBC, we can count on a standard set of database access features and (usually) a particular subset
of SQL, SQL-92. The JDBC API defines a set of interfaces that encapsulate major database
functionality, including running queries, processing results, and determining configuration
information. A database vendor or third-party developer writes a JDBC driver, which is a set of
classes that implements these interfaces for a particular database system. An application can use a
number of drivers interchangeably. Figure 1 show how an application uses JDBC to interact with
one or more databases without knowing about the underlying driver implementations.

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 1 of 9
Technical Article

Figure 1 JDBC-database interaction

Anatomy of JDBC Application:


JDBC API provides interfaces and classes to work with databases. Connection interface
encapsulates database connection functionality, Statement interface encapsulates SQL query
representation and execution functionality and ResultSet interface encapsulates retrieving data
which comes from execution of SQL query using Statement.

The following are the basic steps to write a JDBC program


1. Import java.sql and javax.sql packages
2. Load JDBC driver
3. Establish connection to the database using Connection interface
4. Create a Statement by passing SQL query
5. Execute the Statement
6. Retrieve results by using ResultSet interface
7. Close Statement and Connection

Example:

Let's look at an example that incorporates most of the major pieces of JDBC functionality. Below
example loads a driver, connects to the database, executes some SQL, and retrieves the results. It
also keeps an eye out for any database-related errors.

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 2 of 9
Technical Article

import java.sql.*;

public class JDBCSample {

public static void main(java.lang.String[] args) {


try {
// This is where we load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver Class");
return;
}

try {
// All database access is within a try/catch block. Connect to
database,
// specifying particular database, username, and password
Connection con =
DriverManager.getConnection("jdbc:odbc:companydb",
"username", "password");

// Create and execute an SQL Statement


Statement stmt = con.createStatement( );
ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM
EMPLOYEES");

// Display the SQL Results


while(rs.next( )) {
System.out.println(rs.getString("FIRST_NAME"));
}

// Make sure our database resources are released


rs.close( );
stmt.close( );
con.close( );

}
catch (SQLException se) {
// Inform user of any SQL errors
System.out.println("SQL Exception: " + se.getMessage( ));
se.printStackTrace(System.out);
}
}
}

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 3 of 9
Technical Article

Above example will starts by loading a JDBC driver class (in this case, Sun's JDBC-ODBC Bridge).
Then it creates a database connection, represented by a Connection object, using that driver. With
the database connection, we can create a Statement object to represent an SQL statement.
Executing an SQL statement produces a ResultSet that contains the results of a query. The
program displays the results and then cleans up the resources it has used. If an error occurs, a
SQLException is thrown, so our program traps that exception and displays some of the information
it encapsulates.

JDBC Drivers
Before we can use a driver, it must be registered with the JDBC DriverManager. This is typically
done by loading the driver class using the Class.forName( ) method:

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException e) {
/* Handle Exception */
}

One reason most programs call Class.forName( ) is that this method accepts a String argument,
meaning that the program can store driver selection information dynamically (e.g., in a properties
file).

Another way to register drivers is to add the driver classes to the jdbc.drivers property. To use this
technique, add a line like the following to ~/.hotjava/properties (on Windows systems this file can be
found in ours Java SDK installation directory):

jdbc.drivers=com.oracle.jdbc.OracleDriver:foo.driver.dbDriver:
com.al.AlDriver;

Separate the names of individual drivers with colons and be sure the line ends with a semicolon.
(Programs rarely use this approach, as it requires additional configuration work on the part of end
users.) Every user needs to have the appropriate JDBC driver classes specified in his properties
file.

JDBC drivers are available for most database platforms, from a number of vendors and in a number
of different flavors. There are four categories of drivers:

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 4 of 9
Technical Article

Type 1:- JDBC-ODBC bridge drivers:

Type 1 drivers use a bridge technology to connect a Java client to an ODBC database system.
JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and
sends them to the ODBC driver. Type 1 drivers require some sort of non-Java software (ODBC) to
be installed on the machine running ours code and they are implemented using native code.

Type 1: JDBC-ODBC Bridge

Advantages:

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.

Type 2 Native-API partly Java drivers

Type 2 drivers use a native code library to access a database, wrapping a thin layer of Java around
the native library. For example, with Oracle databases, the native access might be through the

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 5 of 9
Technical Article

Oracle Call Interface (OCI) libraries that were originally designed for C/C++ programmers. Type 2
drivers are implemented with native code, so they may perform better than other drivers, but they
also add an element of risk, as a defect in the native code can crash the Java Virtual Machine.

It converts JDBC calls into database-specific calls for databases such as SQL Server, Informix,
Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it
requires that some binary code be present on the client machine.

Type 2: Native-API/partly Java driver

Advantages:
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.
Disadvantages

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.

Type 3 Net-protocol Pure-Java drivers

Type 3 drivers define a generic network protocol that interfaces with a piece of custom middleware.
The middleware component might use any other type of driver to provide the actual database

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 6 of 9
Technical Article

access. These drivers are especially useful for applet deployment, since the actual JDBC classes
can be written entirely in Java and downloaded by the client on the fly.

It follows a three-tiered approach whereby the JDBC database requests are passed through the
network to the middle-tier server. The middle-tier server then translates the request (directly or
indirectly) to the database-specific native-connectivity interface to further the request to the
database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver
to do this.

Type 3: Net-protocol/all-Java driver

Advantages:

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.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantages:

It requires another server application to install and maintain. Traversing the recordset may take
longer, since the data comes through the backend server.

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 7 of 9
Technical Article

Type 4 Native-protocol Pure-Java drivers

Type 4 drivers are written entirely in Java. They understand database-specific networking protocols
and can access the database directly without any additional software. These drivers are also well
suited for applet programming, provided that the Java security manager allows TCP/IP connections
to the database server.

It converts JDBC calls into the vendor-specific database management system (DBMS) protocol so
that client applications can communicate directly with the database server. Level 4 drivers are
completely implemented in Java to achieve platform independence and eliminate deployment
administration issues.

Type 4: Native-protocol/all-Java driver

Advantages:

1. The major benefit of using type 4 jdbc driver 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. We don’t need to install special software on the client or server. Further, these drivers can
be downloaded dynamically.

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 8 of 9
Technical Article

Disadvantages:

With type 4 drivers, the user needs a different driver for each database.

When we are selecting a driver, we need to balance speed, reliability, and portability. Different
applications have different needs. A standalone, GUI-intensive program that always runs on a
Windows NT system will benefit from the additional speed of a Type 2, native-code driver. An applet
might need to use a Type 3 driver to get around a firewall. A servlet that is deployed across multiple
platforms might require the flexibility of a Type 4 driver.

Conclusion:
JDBC is API which is used to do database operation from java programming language. JDBC
makes it possible to write a single database application that can run on different platforms and
interact with different DBMSs. There are four flavors of JDBC drivers. JDBC offers a wide range of
functionality such as prepared statements for greater performance, stored procedures, scrollable
result sets, batch updates and new data types.

JDBC By Rahul Kumar


Article Code: ACE-10/015 Page 9 of 9

Anda mungkin juga menyukai