JDBC(JAVA DATABASE CONNECTIVITY) •JDBC stands for Java Database Connectivity. •Which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. •The JDBC library includes APIs for each of the tasks associated with database usage WHAT DOES JDBC DO? Simply , JDBC makes it possible to do three things: 1. Establish a connection with a database 2. Send SQL/MYSQL statements (Creating SQL or MySQL statement and executing queries) 3. Process the results (Viewing & Modifying the resulting records) JDBC ARCHITECTURE Java code calls JDBC library (API) JDBC loads a driver Driver talks to a particular database Java Application JDBC API JDBC Driver DBMS/RDB MS JDBC ARCHITECTURE JDBC Architecture consists of two layers: JDBC API: This provides the application-to-JDBC Manager connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application: TYPE 1: JDBC-TO-ODBC BRIDGE Microsoft created ODBC (Open Database Connection), which is the basis from which Sun created JDBC. Both have similar driver specifications and an API. The JDBC-to-ODBC driver, also called the JDBC/ODBC Bridge, is used to translate DBMS calls between the JDBC specification and the ODBC specification. MS Access and SQL Server contains ODBC driver written in C language using pointers, but java does not support the mechanism to handle pointers. So JDBC-ODBC Driver is created as a bridge between the two so that JDBC-ODBC bridge driver translates the JDBC API to the ODBC API. Type-1 ODBC Driver for MS Access and SQL Server Drawbacks of Type-1 Driver: ODBC drivers must be loaded on each client. Translation overhead between JDBC and ODBC. It doesn’t support all features of Java. it is slow compare with other types. Type-1 driver isn’t written in java, that’s why it isn’t a portable driver. TYPE 2: NATIVE-API DRIVER This driver converts JDBC method calls into native calls of the database API. In order to interact with different database, this driver needs their local API. The Java/Native Code driver uses Java classes to generate platform- specific code that is code only understood by a specific DBMS. Ex: Driver for DB2, Informix, Oracle Driver, WebLogic drivers Drawbacks of Type-II Driver: The driver directly communicates with database servers and therefore driver needs to be installed separately in individual client machines Type-2 driver isn’t written in java, that’s why it isn’t a portable driver TYPE 3: NET-PROTOCOL DRIVER OR MIDDLEWARE DRIVER Based on intermediate (middleware) database servers. Connect to various database servers via an intermediate server that acts like a gateway for multiple database servers. The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are present in a single server, hence no need of individual client-side installation. Type-3 drivers are fully written in Java, hence they are portable drivers. Ex: Symantec DB Drawbacks: Network support is required on client machine. Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier. It does not support all network protocols. If the middleware server is failed entire system will be failed. TYPE 4: DATABASE-PROTOCOL DRIVER OR PURE JAVA DRIVER Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not require any native database library, that is why it is also known as Thin Driver. Only disadvantage: need to download a new driver for each database engine Which Driver to use When? If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is type-4. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database. The type 1 driver is not considered a deploymentlevel driver, and is typically used for development and testing purposes only. Components of JDBC DriverManager : It loads database drivers and manages the connection between the application and the driver Driver : It translates API calls into operation for a specific data source. Connection :It is a session between application and a database. Statement : It is an sql statement to perform a query or update operation MetaData : It gives information about returned data, the database Resultset : logical set of columns and rows of data returned by executing a statement. E . BASIC JDBC DATA TYPES Char, varchar and longvarchar The role of the char is to represent a small, fixed length character string. Varchar represents a small , variable-length character string, and Lonvarchar represent a large variable length character string. As a java string, each can be expressed. Binary, VarBinary and Longbinary. The role of the BINARY is to represent a small, fixed-length binary value. Varbinary represents a small, variable-length binary value. Longvarbinary represents a large, variable-length binary value. For retrieving BINARY and VARBINARY values, the method recommended is ResultSet.getBytes. BIT A single bit value is represented by the JDBC type BIT that can be zero or one. For the JDBC BIT type, the recommended Java mapping is as Java boolean. TinyInt An 8-bit integer value, between 0 and 255. Java short will always be able to hold all TINYINT values. SMALLINT A 16-bit signed integer alue between -32768 and 32767. Java mapping is as Java short. INTEGER: A 32-bit signed integer value -21473648 and 2147483647. Java mapping is Java int. BIGINT A 64-bit signed integer value. Java mapping is as Java long. REAL A “ single precision” floating point number. Java mapping as Java float. DOUBLE A “ double precision” floating point number is represented as Java double. DECIMAL AND numeric DECIMAL and NUMERIC which are JDBC types. They both represent fixed-precision decimal values. Java mapping is java.math.BigDecimal. DATE , TIME and TIMESTAMP Jdbc DATE type represents a date consisting of day, month and year. Corresponding java.util. Date The second type is known as JDBC time that represents a time which is consitin of hours, minutes and second. Corresponding java type is java.util.Time. The third type is JDBC TIMESTAMP represents DATE plus TIME plus a nanosecond. Corresponding java type is java.util.Timestamp. ADVANCED JDBC DATA TYPES BLOB datatype Binary Large Object File. Video CLOB data type Character Large Object file. Text files, Stories. User defined types: Structured type: User-defined type; for example: CREATE TYPE PLANE_POINT AS (X FLOAT, Y FLOAT) DISTINCT type: User-defined type based on a builtin type; for example: (typedef in C or C++) CREATE TYPE MONEY AS NUMERIC(10,2) REF(structured-type): Pointer that persistently denotes an instance of a structured type that resides in the database Mapping Advanced Data Types The JDBC API provides default mappings for advanced data types specified . The following list gives the data types and the interfaces or classes to which they are mapped: BLOB: Blob interface CLOB: Clob interface ARRAY: Array interface Structured types: Struct interface REF(structured type): Ref interface Common JDBC Components: The JDBC API provides the following interfaces and classes: DriverManager: This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. Driver: This interface handles the communications with the database server. Connection : This interface with all methods for contacting a database. All communication with database is through connection object only. Statement : We use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects SQLException: This class handles any errors that occur in a database application. http://www.slideshare.net/java2all/jdbc-architecture-anddriver-types JDBC PACKAGES JDBC API is mainly divided into two package 1. java.sql 2. javax.sql java.sql package This package include classes and interface to perform almost all JDBC operation such as creating and executing SQL Queries. Important classes and interface of java.sql package classes/interface java.sql.BLOB java.sql.Connection Description Provide support for BLOB(Binary Large Object) SQL type. creates a connection with specific database java.sql.CallableStatement Execute stored procedures java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type. java.sql.Date Provide support for Date SQL type. java.sql.Driver create an instance of a driver with the DriverManager. This class manages database drivers. java.sql.DriverManager java.sql.PreparedStatement java.sql.ResultSet Used to create and execute parameterized query. It is an interface that provide methods to access the result row-by-row. java.sql.Savepoint Specify savepoint in transaction. java.sql.SQLException Encapsulate all JDBC related exception. java.sql.Statement This interface is used to execute SQL statements. JAVAX.SQL PACKAGE THIS PACKAGE IS ALSO KNOWN AS JDBC EXTENSION API. IT PROVIDES CLASSES AND INTERFACE TO ACCESS SERVER-SIDE DATA. Important classes and interface of javax.sql package classes/interface Description javax.sql.ConnectionEvent Provide information about occurence of event. javax.sql.ConnectionEventListener Used to register event generated by PooledConnectionobject. javax.sql.DataSource Represent the DataSource interface used in an application. javax.sql.PooledConnection provide object to manage connection pools. JDBC - EXCEPTIONS HANDLING JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException. SQLException Methods An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause. The passed SQLException object has the following methods available for retrieving additional information about the exception JDBC - EXCEPTIONS HANDLING Method getErrorCode( ) getMessage( ) Description Gets the error number associated with the exception. Gets the JDBC driver's error message for an error, handled by the driver or gets the Oracle error number and message for a database error. getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null. getNextException( ) Gets the next Exception object in the exception chain. Prints the current exception, or throwable, and it's backtrace to a standard error stream. printStackTrace( ) printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify. printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the print writer you specify. JDBC - EXCEPTIONS HANDLING Exception Handling Approach try{ // all statements including commit }catch(SQLException e) { // rollback or commit if rollback for a given savepoint } Finally{ // close connection or statements or resultsets }