What is a Database Driver?

Database clients use Database Drivers to send SQL statements to the Database Servers and to receive the resultsets and other responses from the server. A Driver Manager manages communication between applications and drivers. What is meant by JDBC Driver? JDBC API contain set of Interfaces to implement. Sun Soft leave this API to third party vendors(DataBase servers like Oracle, MySql, SQL Server) to implement these Intefaces. JDBC Driver : A set of Classes providing the implementation of the Interfaces that are part of the JDBC API is called JDBC Driver. The JBBC Driver vendors provides the Drivers as part of JAR Files. Examples : - ojdbc14.jar : Provided by Oracle corp that contain Classes that deals with Oracle DataBase Server. - mysql-connector-java-3.0.11-stable-bin.jar : Provided by MySQL that contain Classes that deals with MySQL DataBase Server. Difference between Statement and Prepared Statement? Both these Statements purpose is same. These both send a SQL Queries (which we passed to these Statement Objects) to DataBase Server and asked the DBserver to execute the queries. When a Query sent to DBServer, then at the server side, The DBServer does two tasks: 1. Parsing: Split the Statement into pieces and verifying whether that Query followed the grammar and syntax of SQL language or not. It generates a pseudo code for the query. 2. Execution : After verifying Query, if it is not violated the SQL language syntax and grammar, then the DBServer will execute the statement (means perform the appropriate task) and send response to JDBC Driver, The Driver then return back the same response to Client (in which our Java Code running). So when a Query sent to DB, these two tasks will be done by DB every time. See here Difference :

Three Sql queries same syntax but the values are different : String s1 = "insert into employee values (100, 'ramu');" String s2 = "insert into employee values (101, 'ravi');" String s3 = "insert into employee values (102, 'raghu');" When we are using Statement : Statement stmt = con.createStatement(); Client side sending Queries ---------- DBServer side stmt.executeUpdate(s1); ----------- parsing + Execution stmt.executeUpdate(s2); ----------- parsing + Execution stmt.executeUpdate(s3); ----------- parsing + Execution When we are using Statement : - Replace those 3 SQL Queries with a single Query with positional Paremeters see bellow String s = "insert into employee values (?, ?);" ParepareStatement pstmt = con.preparedStatement(s); Client side sending Queries ---------- DBServer side pstmt.setInt(1,100); pstmt.setString(2,"ramu"); pstmt.executeUpdate() ---------- parsing + Execution (at First Time) pstmt.setInt(1,101); pstmt.setString(2,"ravi"); pstmt.executeUpdate() -------- Only Execution (From second time onwards) pstmt.setInt(1,102); pstmt.setString(2,"raghu"); pstmt.executeUpdate() -------- Only Execution So when we are using PrepareStatemt, then parsing will be done only once, the next time onwards DBServer will take the values and execute the Query (which it has parsed earlier) with those value. So here advantage is that reducing burden of DBServer. Purpose of Batch Update Statement? Batch Update : When we want to send more than one SQL Queries to DB Server to perform some task, then at that situation instead of sending the Queries independently send them once by grouping them (as bulk). So to group the more than one Queries into

one batch we can use Batch Update. Advantage: when we are sending the Queries independently the more amount of time will be wasted and more data will be transferred between DBServer and Client, it's some what burden to those Client and DBServer. So if we use Batch Update then we can send those Queries only once as a bulk, it reduces the time and burden. Example : String s1 = "insert into employee values (100, 'ramu');" String s2 = "insert into employee values (101, 'ravi');" String s3 = "insert into employee values (102, 'raghu');" Statement stmt = con.createStatement(); try { stmt.clearBatch(); stmt.addBatch(s1); stmt.addBatch(s2); stmt.addBatch(s3); stmt.executeBatch(); con. commit(); } catch (exception e) { con.rollback(); } How can we maintain Transaction Management while using BatchUpdate ? - The method executeBatch() submits stmt's list of commands to the underlying DBMS for execution. - The DBMS executes each command in the order in which it was added to the batch and returns an update count for each command in the batch, also in order. If one of the commands does not return an update count, its return value cannot be added to the array of update counts that the method executeBatch() returns. In this case, the method executeBatch() will throw a BatchUpdateException. This exception keeps track of the update counts for the commands that executed successfully before the error occurred, and the order of these update counts likewise follows the order of the commands in the batch. We can maintain Transaction Management by using try/catch block. If a BatchUpdateException is thrown, we can rollback all the transactions which have done previously. Otherwise we commit the all transaction by writing the con.commit() in try block.

Example : Code:
con.setAutoCommit(false); try { stmt.addBatch("INSERT INTO employees VALUES (" + "1000, 'Joe Jones')"); stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')"); stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')"); int [] updateCounts = stmt.executeBatch(); con.commit(); } catch(BatchUpdateException b) { System.err.println("Update counts of successful commands: "); int [] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i ++) { System.err.print(updateCounts[i] + " "); con.rollback(); } System.err.println(""); }

Different types of driver in JDBC? There are four types of drivers : Type 1 - Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge driver is an example of a Type 1 driver. Type 2 - drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Type 3 - drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client?s requests to the data source. Type 4 - drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source. What are the Interfaces are there in JDBC API ? Sun Soft has provided a set of Interfaces, those are included in two different types of packages 1. java.sql.* : Provides the API for accessing and processing data stored in a Data Source (usually a relational database) using the Java.

2. javax.sql.* : Provides the API for server side Data Source access and processing from the Java. java.sql Package contain bellow Interfaces : CallableStatement : The interface used to execute SQL stored procedures. Connection : A connection (session) with a specific database. DatabaseMetaData : Comprehensive information about the database as a whole. Driver : The interface that every driver class must implement. PreparedStatement : An object that represents a precompiled SQL statement. ResultSet : A table of data representing a database result set, which is usually generated by executing a statement that queries the database. ResultSetMetaData : An object that can be used to get information about the types and properties of the columns in a ResultSet object. Statement : The object used for executing a static SQL statement and returning the results it produces. What the java.sql Package Contains? The java.sql package contains API for the following : - Making a connection with a database via the DriverManager facility DriverManager class -- makes a connection with a driver SQLPermission class -- provides permission when code running within a Security Manager, such as an applet, attempts to set up a logging stream through the DriverManager Driver interface -- provides the API for registering and connecting drivers based on JDBC technology ("JDBC drivers"); generally used only by the DriverManager class DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the general user - Sending SQL statements to a database Statement -- used to send basic SQL statements

PreparedStatement -- used to send prepared statements or basic SQL statements (derived from Statement) CallableStatement -- used to call database stored procedures (derived from PreparedStatement) Connection interface -- provides methods for creating statements and managing connections and their properties Savepoint -- provides savepoints in a transaction - Metadata DatabaseMetaData interface-- provides information about the database ResultSetMetaData interface -- provides information about the columns of a ResultSet object ParameterMetaData interface -- provides information about the parameters to PreparedStatement commands - Exceptions SQLException -- thrown by most methods when there is a problem accessing data and by some methods for other reasons SQLWarning -- thrown to indicate a warning DataTruncation -- thrown to indicate that data may have been truncated BatchUpdateException -- thrown to indicate that not all commands in a batch update executed successfully

What is JDBC Driver Manager ? 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. The Standard Extension packages javax.naming and javax.sql let you use a DataSource

object registered with a Java Naming and Directory Interface(JNDI) naming service to establish a connection with a Data Source. - We can use either connecting mechanism, but using a DataSource object is recommended whenever possible. What are the Steps for getting Connection from Data Base? Step1 : Loadind Driver. Step2 : Register the Driver. Step3 : Specify your database name. Calling the Class.forName automatically creates an instance of a Driver and Registers it with the DriverManager, so you don't need to create an instance of the class. Step4 : Open Connection. Step5 : Execute your sql querie. Step6 : Getting Result. How can we close Statement ? Statement objects will be closed automatically by the Java Garbage Collector. Nevertheless, it is recommended as good programming practice that they be closed explicitly when they are no longer needed. This frees DBMS resources immediately and helps avoid potential memory problems. What is a Callable Statement ? A CallableStatement object provides a way to call Stored Procedures in a standard way for all RDBMSs. Stored Procedure : A Stored Procedure is stored in a DataBase. The call to the Stored Procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms : 1. Form with a result parameter 2. Without result parameter. - A result parameter, a kind of OUT parameter, is the return value for the Stored Procedure. - Both forms may have a variable number of parameters used for input (IN parameters), output (OUT parameters), or both (INOUT parameters).

- A question mark serves as a placeholder for a parameter. Syntax : The syntax for invoking a Stored Procedure using the JDBC API is shown here. {call procedure_name[(?, ?, ...)]} Note : The square brackets indicate that what is between them is optional; they are not themselves part of the syntax. - The syntax for a procedure that returns a result parameter is : {? = call procedure_name[(?, ?, ...)]} - The syntax for a Stored Procedure with no parameters would look like this : {call procedure_name} Normally, anyone creating a CallableStatement object would already know that the DBMS being used supports Stored Procedures and what those procedures are. - If one needed to check, however, various DatabaseMetaData methods will supply such information. For instance, the method supportsStoredProcedures() will return true if the DBMS supports Stored Procedure calls, and the method getProcedures() will return a description of the Stored Procedures available. How can we create a Callable Statement Object ? CallableStatement objects are created with the Connection method prepareCall(). Example : See con is an active JDBC Connection object, creates an instance of CallableStatement. CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}"); - The variable cstmt contains a call to the Stored Procedure getTestData(), which has two input parameters and no result parameter. Whether the ? placeholders are IN, OUT, or INOUT parameters depends on the Stored Procedure getTestData. - This instance of a CallableStatement object was created using JDBC 1.0 API; consequently, any query in the Stored Procedure called by cstmt will produce a default ResultSet object (one that is non-scrollable and non-updatable).

- The JDBC 2.0 API provides the means to create CallableStatement objects that can produce ResultSet objects that are Scrollable and Updatable, as the following code fragment demonstrates. Example : String sql = "{call getTestData(?, ?)}"; CallableStatement cstmt2 = con.prepareCall(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); The variable cstmt2 contains the same call to the Stored Procedure TestData that cstmt does, but with cstmt2, any ResultSet objects that TestData produces can be Updated and are Scrollable. How to create different types of ResultSets ? A ResultSet is created by executing a query, and the type of ResultSet depends on the arguments that are supplied to the Connection method createStatement (or prepareStatement or prepareCall). The following code fragment, which uses only JDBC 1.0 API, supplies no arguments to the method createStatement() and thus creates a default ResultSet object, one that is forward-only and uses read-only concurrency. Example : Code:
Connection con = DriverManager.getConnection("jdbc:my_subprotocol:my_subname"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT EMP_NO, SALARY FROM EMPLOYEES");

- The variable rs represents a ResultSet object that contains the values for the columns EMP_NO and SALARY from every row in the table EMPLOYEES. This ResultSet is Not Scrollable, so only the method next() can be used to move the cursor from the top down through the rows of the ResultSet. The ResultSet object rs cannot be updated. We can use the new JDBC 2.0 core API to create a Scrollable ResultSet that is Sensitive to updates (by specifying ResultSet.TYPE_SCROLL_SENSITIVE) and that is updatable (by specifying ResultSet.CONCUR_UPDATABLE). Example : Code:

Connection con = DriverManager.getConnection("jdbc:my_subprotocol:my_subname"); Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setFetchSize(25); ResultSet rs2 = stmt.executeQuery("SELECT EMP_NO, SALARY FROM EMPLOYEES");

- The variable rs2 contains the same values as rs, from the previous example, but unlike rs, it is Scrollable, Updatable, and Sensitive to changes in the underlying table's data. It also hints that the driver should fetch 25 rows from the DataBase each time new rows are needed. Each time the Statement object stmt is executed, it will create a ResultSet that is Scrollable, is Updatable, is Sensitive to changes in its data, and has a fetch size of 25. The ResultSet may change its fetch size, but it cannot change its type or concurrency. Note : There is a cost to making a ResultSet Scrollable or Updatable, so it is good practice to create ResultSets with these features only when they are needed. How to get number of rows in a table using Scroable ResultSet ? This will happens by moving the cursor to the last row of the Result set and call the method ResultSet.getRow(). Example : Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = stmt.executeQuery("SELECT * FROM myTest"); // Move to the end of the result set resultSet.last(); // Get the row number of the last row which is also the row count int rowCount = resultSet.getRow(); Here rowCount gives you total number of rows exist on your table. 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. - It is limited to running locally - Must have ODBC installed on computer

- Must have ODBC driver for specific Database installed on computer - Generally can't run inside an applet because of Native Method calls

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. 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. - Uses Native Database library on computer to access DataBase - Generally can’t run inside an Applet because of Native Method calls - Must have DataBase library installed on client Example : DB-lib for Sybase, Oracle, MS-SQL server

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. Type 3 JDBC Driver : All Java/Net-protocol driver 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. - 100% Java Driver, NO Native Methods - Does not require pre-installation on client - Can be downloaded and configured 'on-the-fly' just like any Java Class File - Uses a proprietary protocol for talking with a middleware server - Middleware server converts from proprietary calls to DBMS specific calls

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 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. Type 4 JDBC Driver : Native-Protocol/All-Java Driver The Type 4 uses Java networking libraries to communicate directly with the DataBase Server. - 100% Java Driver, no Native Methods - Does not require pre-installation on client - Can be downloaded and configured 'on-the-fly’'just like any Java Class File - Unlike Type 3 Driver, talks DIRECTLY with DBMS Server - Converts JDBC calls directly to DataBase specific calls

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.