Sunteți pe pagina 1din 16

JDBC

WHAT IS JDBC?
JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the data base. The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture. Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.

WHAT JDBC DO ?
It helps to connect to the database. It helps to execute queries and updating statements to the database. Retrieving and processing the results received from the database in terms of answering to your query. There are three main steps to access Data Base using JDBC Load JDBC Driver for Data base. If you want to connect ORACLE then you have to load ORACLE Driver. If MySQL then MySQL Driver. Get Connection from Driver Manager. Execute the Query AND access the results.

JDBC ARCHITECTURE
JDBC is a core part of the Java platform and is included in the standard JDK distribution. Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.

A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. The purpose of JDBC is to connect Data base and manipulate the data in Data Base. The main components in JDBC are: 1. 2. 3. 4. 5. 6. 7. 8. Database connections SQL statements Result Set Database metadata Prepared statements Binary Large Objects (BLOBs) Character Large Objects (CLOBs) Callable statements

9. Database drivers 10. Driver manager

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.

1. Loading a database driver


In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName (String ClassName) method is Class. Class is a class in java.lang package. try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver } catch(Exception x){ System.out.println( Unable to load the driver class! ); }

2.

Creating

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. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions. JDBC URL Syntax:: jdbc: <subprotocol>: <subname> JDBC URL Example:: jdbc: <subprotocol>: <subname> Each driver has its own subprotocol.

Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.

try{ Connection dbConnection=DriverManager.getConnection(url,loginName,Password) } catch( SQLException x ){ System.out.println( Couldnt get connection! ); }

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.

Three kinds of Statements:


Statement: Execute simple sql queries 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. without parameters.

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.

Test JDBC Driver Installation


import javax.swing.JOptionPane; public class TestJDBCDriverInstallation_Oracle { public static void main(String[] args) { StringBuffer output = new StringBuffer(); output.append(Testing oracle driver installation \n); try { String className = sun.jdbc.odbc.JdbcOdbcDriver; Class driverObject = Class.forName(className); output.append(Driver : +driverObject+\n); output.append(Driver Installation Successful); JOptionPane.showMessageDialog(null, output); } catch (Exception e) { output = new StringBuffer(); output.append(Driver Installation FAILED\n); JOptionPane.showMessageDialog(null, output); System.out.println(Failed: Driver Error: + e.getMessage()); } } }

JDBC RESULT SETS


ResultSet and Cursors
The rows that satisfy a particular query are called the result set. The number of rows returned in a result set can be zero or more. A user can access the data in a result set using a cursor one row at a time from top to bottom. A cursor can be thought of as a pointer to the rows of the result set that has the ability to keep track of which row is currently being accessed. The JDBC API supports a cursor 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. The JDBC Resultset example is shown in the next sections to follow.

Types of Result Sets


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 result set type, result set concurrency, and cursor holdability. 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 the ResultSet object is determined by one of three different ResultSet types: TYPE_FORWARD_ONLY the result set is not scrollable i.e. the cursor moves only forward, from before the first row to after the last row. TYPE_SCROLL_INSENSITIVE the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. TYPE_SCROLL_SENSITIVE the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(..); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is readonly or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

RESULT SET METHODS

When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, you can use the following methods: 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 backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. 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 n) - positions the cursor on the n-th row of the ResultSet object.

JDBC DRIVER TYPES

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: AllJava/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver


JDBC-ODBC Bridge driver 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.

Type 1: JDBC-ODBC Bridge

Advantages:
The JDBC-ODBC Bridge allows access to almost any database, since the databases ODBC drivers are already available.

Disadvantages:

Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 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. The client system requires the ODBC Installation to use the driver. Not good for the Web.

Type 2 JDBC Driver


Native-API/partly Java driver 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 will have oracle native api.

Type 2: Native api/ Partly Java Driver

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

Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. Like Type 1 drivers, its not written in Java Language which forms a portability issue. If we change the Database we have to change the native api as it is specific to a database. Mostly obsolete now. Usually not thread safe.

Type 3 JDBC Driver


All Java/Net-protocol driver Type 3 database requests are passed through the network to the middle-tier server. The middletier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Type 3: All Java/ Net-Protocol Driver

Advantages:
This driver is server-based, so there is no need for any vendor database library to be present on client machines. This driver is fully written in Java and hence Portable. It is suitable for the web. There are many opportunities to optimize portability, performance, and scalability. The net protocol can be designed to make the client JDBC driver very small and fast to load. 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. This driver is very flexible allows access to multiple databases using one driver. 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.

Type 4 JDBC Driver


Native-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server.

Type 4: Native-protocol/all-Java driver

Advantages:
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. Number of translation layers is very less i.e. type 4 JDBC drivers dont 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. You dont 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.

THE JDBC DRIVER MANAGER

The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. These are the steps happing inside to get Connection

Step 1.
Class.forName("com.mysql.jdbc.Driver") load the Driver.

Step 2.
In the com.mysql.jdbc.Driver class there is static bock . That will execute because of static bock. static { try { DriverManager.registerDriver(new Driver()); } catch(SQLException E) { throw new RuntimeException("Can't register driver!"); } } This static block call DriverManager.registerDriver(new Driver());

Step 3.
Inside DriverManager.registerDriver() method. public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException{ DriverInfo di = new DriverInfo(); di.driver = driver; di.driverClass = driver.getClass(); di.driverClassName = di.driverClass.getName(); drivers.addElement(di); println("registerDriver: " + di); } DriverManager class create a Vector name drivers and add the Driver class to the vector. Now In the Vector we have com.mysql.jdbc.Driver object.

Step 4.

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB",username,password); In this method , it search the Driver in the vector , if available then connect and return connection. for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // if ?jdbc:mysql? keywork withic in input , match with the driver in the vector { Connection result = di.driver.connect(url, info); } } Return connection; This class getting jdbc:mysql://localhost:3306/testDB as input . This class check for the driver based on ?jdbc:mysql? in this case and connect the driver. The DriverManager class works between the user and the drivers. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing messages. This class is mainly useful for the simple application, the most frequently used method of this class is DriverManager.getConnetion(). We can know by the name of the method that this method establishes a connection to a database. The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver(). By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads. This class has many methods. Some of the commonly used methods are given below: 1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class. 2. registerDriver(Driver driver) : It registers the driver with the DriverManager class. 3. getConnection(String url) : It tries to establish the connection to a given database URL. 4. geConnection(String url, Sting user, String password) : It tries to establish the connection to a given database URL. 5. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL. 6. getDriver(String url) : It attempts to locate the driver by the given string. 7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class.

JDBC VERSIONS
1). The JDBC 1.0 API. 2). The JDBC 1.2 API. 3). The JDBC 2.0 Optional Package API. 4). The JDBC 2.1 core API. 5) The JDBC 3.0 API. 6) The JDBC 4.0 API.

Features of JDBC 1.0 API


The JDBC 1.0 API was the first officially JDBC API launched consists of the following java classes and interfaces that you can open connections to particular databases. This version includes a completely redesigned administration console with an enhanced graphical interface to manage and monitor distributed virtual databases.

Features of JDBC 1.2 API


It supports Updatabale ResultSets. The DatabaseMetaData code has been refactored to provide more transparency with regard to the underlying database engine. New pass through schedulers for increased performance.

Features of The JDBC 2.0 Optional Pacakage API


The use of DataSource interface for making a connection. Use of JNDI to specify and obtain database connections. It allows us to use Pooled connections, that is we can reuse the connections. In this version the distrbuted transactions is possible. It provides a way of handling and passing data using Rowset technology.

Features of the JDBC 2.1 core API.


Scroll forward and backward in a result set or has the ability to move to a specific row. Instead of using SQL commands, we can make updates to a database tables using methods in the Java programming language We can use multiple SQL statements in a a database as a unit, or batch.