JDBC


JDBC Architecture:-


The following Architecture of JDBC Applications. 


 
From the above architecture we have to develop the java application which communications with DB server.
Sun Micro System as released two packages for JDBC. They are:
1.     Java.sql
2.     Javax.sql

The following are the most important of class and interface java.sql package.

***java.sql interfaces

1.     Driver
2.     Connection
3.     Statement
4.     PreparedStatement
5.     CallableStatement
6.     ResultSet
7.     DatabaseMetadata
8.     ResultSetMetadata

***java.sql classes:

1.     DriverManager
2.     Types
3.     Date

The most important (classes and) interfaces of javax.sql packages are:

**javax.sql interfaces:

1.     DataSource
2.     RowSet

Once the API released so many people has provide the implementation to JDBC API, we call the implementation as JDBC Driver. We can use any company JDBC Driver to develop the application.






All the above companies release JDBC Driver software in the form of jar files.
We have to use this jar files to develop the java application to communicate with database server.
We have to following the procedure to develop a java application which communicate with DB server.
1.     Register the JDBC Driver.
2.     Get the Connection from the Database Server.
3.     Create the Statement Object.
4.     Execute the Query’s.
5.     Close the Connection.

*What is Driver class?
A class which provides an implementation of JDBC Driver interface is called as Driver class.
The name of the class varying from Driver to Driver we can find Driver class name in manual.

imprort java.sql.*;
public class RegisterDriver{
public static void main(String[] args)throws SQLException{
Driver d = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
 
System.out.println(“Driver is Register”);
           }
}


*The following JDBC program established connection with Oracle DB server.

import java.sql.*;
public class DatabaseConnection{
public static void main(String[] args)throws SQLException{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection
                                                (“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”malli”);
System.out.println(“got the connection:” + con.getClass());         
            }
}
If we got the connection object successfully we can say the java program establish with connectivity database server. It we fail to get the connection it throws an Exception java.sql.Exception.


*Requirement:

Develop a java program to create a table in the database server. The table name must be emp with eno, ename, salary as columns names.

import java.sql.*;
public class CreateTable{
public static void main(String[] args)throws SQLException{

//step1: Register the JDBC Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

//step2: get the connection from the DB Server
Connection con = DriverManager.getConnection
                                                (“jdbc:oracle:thin:@localhost:1521:xe”,”system”,”malli”);

//step3: create the statement object
Statement stmt = con.createStatement();

//step4: execute the query
stmt.executeUpdate(“ create table emp(eno number(3), ename varchar2(15),
                                                                                                                salary number(5)”);
//step5: close the connection
Stmt.close();
           }
}




                                   


Introduction to JDBC:

JDBC stands for Java Database Connectivity allows developers to connect, query and update a database using the Structured Query Language. JDBC API standard provides Java developers to interact with different RDBMS and access table data through Java application without learning RDBMS details and using Database Specific JDBC Drivers.

2.  JDBC Architecture

JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database:

open connection to database,

use JDBC driver to send SQL queries to database,

process the results that are returned, and

close the connection.

JDBC uses two architectures to communicate with database:

1) The driver connects to database and executes SQL statements. Results are sent back from driver to driver manager and finally to the application.
2) The JDBC driver communicates with ODBC driver. ODBC driver executes SQL query and then results are sent back to JDBC driver to driver manager and then to application.


Types of JDBC Drivers:

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)

4 types of jdbc drivers are elaborated in detail as shown below:

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
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.
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
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.
Type 3: All Java/ Net-Protocol Driver
Advantage
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.
Type 4: Native-protocol/all-Java driver
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.

JDBC Callable Statement:
The CallableStatement interface allows the use of SQL statements to call stored procedures. Stored procedures are programs that have a database interface. These programs possess the following:
1)    They can have input and output parameters, or parameters that    are   both input and output.
2)    They can have a return value.
3)    They have the ability to return multiple ResultSets.

        Conceptually in JDBC, a stored procedure call is a single call to the database, but the program associated with the stored procedure may process hundreds of database requests. The stored procedure program may also perform a number of other programmatic tasks not typically done with SQL statements.

        Creating CallableStatements

        The prepareCall method is used to create new CallableStatement objects. As with the prepareStatement method, the SQL statement must be supplied at the time that the CallableStatement object is created. At that time, the SQL statement is precompiled. For example, assuming a Connection object named conn already exists, the following creates a CallableStatement object and completes the preparation phase of getting the SQL statement ready for processing within the database:

            
        PreparedStatement ps = conn.prepareStatement("? = CALL ADDEMPLOYEE(?, ?, ?");


        Handling parameters

        As stated, CallableStatement objects may take three types of parameters:

            IN

            IN parameters are handled in the same manner as PreparedStatements. The various set methods of the inherited PreparedStatement class are used to set the parameters.

            OUT

            OUT parameters are handled with the registerOutParameter method. The most common form of registerOutParameter takes an index parameter as the first parameter and an SQL type as the second parameter. This tells the JDBC driver what to expect for data from the parameter when the statement is processed. There are two other variations on the registerOutParameter method that can be found in the java.sql package Javadoc.

            INOUT

            INOUT parameters require that the work for both IN parameters and OUT parameters be done. For each INOUT parameter, you must call a set method and the registerOutParameter method before the statement can be processed. Failing to set or register any parameter results in an SQLException being thrown when the statement is processed.

        Using callable Statement methods to call stored methods:

        To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are:

        --->Invoke the Connection.prepareCall method to create a CallableStatementobject.
        --->Invoke the CallableStatement.setXXX methods to pass values to the input (IN) parameters.
        --->Invoke the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters.
        --->Invoke one of the following methods to call the stored procedure: 
        --->CallableStatement.executeUpdate
        --->Invoke this method if the stored procedure does not return result sets.
        --->

        1. --->CallableStatement.executeQuery
          Invoke this method if the stored procedure returns one result set.
          CallableStatement.execute
          Invoke this method if the stored procedure returns multiple result sets.



        2. --->If the stored procedure returns result sets, retrieve the result sets. SeeRetrieve multiple result sets from a stored procedure in a JDBC application.



        3. --->Invoke the CallableStatement.getXXX methods to retrieve values from the OUT parameters or INOUT parameters.



        4. --->Invoke the CallableStatement.close method to close theCallableStatement object when you have finished using that object.
        The following code illustrates calling a stored procedure that has one input parameter, four output parameters, and no returned ResultSets. The numbers to the right of selected statements correspond to the previously-described steps. 


        JDBC-Simple statement:

        The Statement interface lets you execute a simple SQL statement with no parameters. The SQL instructions are inserted into the Statement object when the Statement.executeXXX method is called.

        Query Statement: This code segment creates a Statement object and calls the Statement.executeQuery method to select text from the dba database. The results of the query are returned in a ResultSet object. How to retrieve results from a ResultSet object is explained in Result Sets below.



        Statement stmt = con.createStatement();
         ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba ");


        Update Statement: This code segment creates a Statement object and calls the Statement.executeUpdate method to add an email address to a table in the dba database.

          String updateString =  "INSERT INTO dba VALUES (some text)";
          int count = stmt.executeUpdate(updateString);

        Java Prepared Statements:

        ava JDBC Prepared statements are pre-compiled SQL statements. Precompiled SQL is useful if the same SQL is to be executed repeatedly, for example, in a loop. Prepared statements in java only save you time if you expect to execute the same SQL over again. Every java sql prepared statement is compiled at some point. To use a java preparedstatements, you must first create a object by calling the Connection.prepareStatement() method. JDBC PreparedStatements are useful especially in situations where you can use a for loop or while loop to set a parameter to a succession of values. If you want to execute a Statement object many times, it normally reduces execution time to use a PreparedStatement object instead.

        The syntax is straightforward: just insert question marks for any parameters that you'll be substituting before you send the SQL to the database. As with CallableStatements, you need to call close() to make sure database resources are freed as soon as possible. Below is a JDBC Program showing the use of jdbc prepared statements to insert data into tables using jdbc programming.
        You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class. There is a setXXX method for each primitive type declared in the Java programming language.

        PreparedStatement pstmt = con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");
        pstmt.setInt(2, 100);
        pstmt.setString(1, "Bob");
        pstmt.executeUpdate();

        An important feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. This SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
        Using Prepared Statements in jdbc, objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.


        1. How will you retreive database warnings from a Connection object in JDBC? 


        //Retrieving warning from connection object
        SQLWarning warning = conn.getWarnings();

        //Retrieving next warning from warning object itself
        SQLWarning nextWarning = warning.getNextWarning(); 


        2. How will you retreive database warnings from a Statement object in JDBC? 


        //Retrieving warning from statement object
        stmt.getWarnings();

        //Retrieving next warning from warning object itself
        SQLWarning nextWarning = warning.getNextWarning();


        3. How will you retreive database warnings from a ResultSet object in JDBC? 

        //Retrieving warning from resultset object
        rs.getWarnings();

        //Retrieving next warning from warning object itself
        SQLWarning nextWarning = warning.getNextWarning(); 


        4. What does the clearWarnings() method do? 

        A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. 

        5. What happens when I try to call the getWarning() method on a connection/statement/resultset after it has been closed? 

        Trying to call the getWarning() method on either of these 3 objects after they are closed will cause an SQLException to be thrown. 

        6. Let us say that I just closed my Statement object so, I cannot access the getWarning() on my statement. Can I still access the getWarning() on my ResultSet? 

        No. Closing a Statement automatically closes the ResultSet connected to it. So, you will get the same SQLException if you try to do so. 

        7. What is DatabaseMetaData? 

        JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of aDatabase Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Use DatabaseMetaData to find information about your database, such as its capabilities and structure.

        8. How will you use the DatabaseMetaData? Can you write a sample example code? 


        DatabaseMetaData md = conn.getMetaData();
        System.out.println("Database Name: " + md.getDatabaseProductName());
        System.out.println("Database Version: " + md.getDatabaseProductVersion());
        System.out.println("Driver Name: " + md.getDriverName());
        System.out.println("Driver Version: " + md.getDriverVersion()); 


        9. What is ResultSetMetaData? 

        JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. 

        10. How will you use the ResultSetMetaData? Can you write a sample example code? 


        ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME");
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        boolean b = rsmd.isSearchable(1); 



        11. What is rowset? 

        A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. 

        12. Why do we need a RowSet?

        RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet

        13. What are the advantages of using RowSet over ResultSet?

        There are two clear advantages of using RowSet over ResultSet: 

        * RowSet makes it possible to use the ResultSet object as a JavaBeans component. 
        * RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

        14. What are the different types of RowSet ? 
        There are two types of RowSet are there. They are: 
        Connected - A connected RowSet object connects to the database once and remains connected until the application terminates. 
        * Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the databaseand then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

        15. Can you give an example of Connected RowSet? 

        A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver. 

        16. Can you give an example of Disconnected RowSet?

        A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA). 

        17. What are the benefits of having JdbcRowSet implementation? 

        The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet 
        * This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. 
        * It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object. 

        18. What is the need of BatchUpdates feature in JDBC? 

        The BatchUpdates feature allows us to group SQL statements together and send to database server in one single shot instead of multiple calls.

        19. What is a DataSource? 

        A DataSource object is the representation of a source of data in the Java programming language. 

        In basic terms: 
        * A DataSource is a facility for storing data. 
        * DataSource can be referenced by JNDI. 
        * Data Source may point to RDBMS, file System , any DBMS etc..

        Typically in enterprise application perspective, the term DataSource can be used interchangeably with a RDBMS database because in almost all cases, our DataSource will be pointing to an RDBMS database. 

        20. What are the advantages of DataSource? 

        The few advantages of using data source are : 
        * An application does not need to hardcode driver information, as it does with the DriverManager. 
        * The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details. 
        * The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions. 

        21. What is the difference between a Statement and a PreparedStatement? 

        Some of the main differences between a statement & PreparedStatement are: 

        StatementPreparedStatment
        A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database.A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
        Statement has to verify its metadata against the database every time.A prepared statement has to verify its metadata against the database only once.
        If you want to execute the SQL statement once go for STATEMENTIf you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.
        22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE in ResultSets? 

        Some of the main differences between a TYPE_SCROLL_INSENSITIVE & TYPE_SCROLL_SENSITIVE are: 

        TYPE_SCROLL_INSENSITIVETYPE_SCROLL_SENSITIVE
        An insensitive resultset is like the snapshot of the data in the database when query was executed.A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
        After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.After we obtain the resultset if the data is modified then such modifications are visible through resultset.
        Performance not effected with insensitive.Since a trip is made for every ‘get’ operation, the performance drastically get affected.
        If you have any questions that you want answer for - please leave a comment on this page and I will answer them. 

        If you have any more questions on JDBC that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

        No comments:

        Post a Comment