Showing posts with label JDBC. Show all posts
Showing posts with label JDBC. Show all posts

Java J2EE Spring How many Types of Statements in JDBC ?

In JDBC there are three types of Statements:

1).Statement
2).PreparedStatement
3).CallableStatement

Once a connection is obtained we can interact with the database.These three are Interfaces.By using these three statements we can do the operations on Databases using the methods provided in Interfaces.

Statement: Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement   : Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.

CallableStatement   : Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.

Java J2EE Spring Java Prepared Statements

Java 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.


Spring Hibernate Java Database Connectivity - JDBC


JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems. The purpose of this article is to give you an introductory overview of this JDBC concept. Before we go any further, let me reiterate that JDBC in itself is a very large topic and what you see in this

Spring Hibernate Top 10 JDBC Best Practices for Java Programmer

Java JDBC Best practices
JDBC Best Practices are some coding practices which Java programmer should follow while writing JDBC code. As discussed in how to connect to Oracle database from Java, JDBC API is used to connect and interact with a Database management System.  We have touched some of the JDBC best practices in our last article 4 JDBC Performance tips, On which we have discussed simple tips to improve performance of Java application with database. By using JDBC you can execute DDL, DML and Stored Procedures. JDBC Best practices is probably most significant set of coding practices in Java because it significantly affect performance of Java application. I have seen substantial performance gain by simply following common JDBC best practices like running queries with auto commit mode disable. One of the query which we used in our example of JDBC Batch update was taking almost 30 second to finish with auto commit mode enabled but it just took under one second with auto commit mode disable and using explicit commit. This JDBC tutorial is collection of such practices which help you to write better JDBC code and in most cases result in improved performance.
Read more »

Spring Hibernate What is difference between java.sql.Time, java.sql.Timestamp and java.sql.Date - JDBC interview Question

Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date  is most common JDBC question appearing on many core Java interviews. As JDBC provides three classes java.sql.Date, java.sql.Time and java.sql.Timestamp to represent date and time and you already have java.util.Date which can represent both date and time, this question poses lot of confusion among Java programmer and that’s why this is one of those tricky Java questions which is tough to answer. It becomes really tough if differences between them is not understood correctly. We have already seen some frequently asked or common JDBC questions like why JDBC has java.sql.Date despite java.util.Date and Why use PreparedStatement in Java in our last tutorials and we will see difference between java.sql.Date, java.sql.Time and java.sql.Timestamp in this article. By the way apart from these JDBC interview questions, if you are looking to get most from JDBC you can also see 4 JDBC performance tips and 10 JDBC best practices to follow. Those article not only help you to understand and use JDBC better but also help on interviews. Let’s come back to difference sql time, timestamp and sql date.
Read more »

Java J2EE Spring JDBC Vs Hibernate


7.1 Why is Hibernate better than JDBC

1)   Relational Persistence for JAVA

Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

2)   Transparent Persistence

The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

3)   Support for Query Language

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

4)   Database Dependent Code

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

5)   Maintenance Cost

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

6)   Optimize Performance

Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many


times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.

7)   Automatic Versioning and Time Stamping

By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

8)   Open-Source, Zero-Cost Product License

Hibernate is an open source and free to use for both development and production deployments.

9)   Enterprise-Class Reliability and Scalability

Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. JDBC can not be scaled easily.

Java J2EE Spring 3. Interaction with RDBMS

General steps:

1) Load the RDBMS specific JDBC driver because this driver actually communicates with the database.
2) Open the connection to database which is then used to send SQL statements and get results back.
3) Create JDBC Statement object. This object contains SQL query.
4) Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.

5) Process the result set.
6) Close the connection.

Example: Retrieve list of employees from Employee table using JDBC.

String url = “jdbc:odbc:” + dbName;

List employeeList = new ArrayList();

/* load the jdbc-odbc driver */ class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

/* Open a connection to database */

Connection con = DriverManager.getConnection(url);

/* create Statement object */

Statement stmt = con.createStatement();

/* execute statement */

ResultSet rs = stmt.executeQuery("SELECT * FROM Sells"); while ( rs.next() )
{
EmployeeBean eb = new Employeebean(); eb.setName(rs.getString("name")); eb.setSalary(rs.getFloat("salary")); employeeList.add(eb);

}

Java J2EE Spring 1. 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.



1. Introduction to JDBC
2. JDBC Architecture 
3. Interaction of JDBC with Database 
4. Introduction to Hibernate 
5. Hibernate Architecture 
6. Hibernate Communication with RDBMS 
7. Hibernate vs. JDBC 
7.1. Advantage of Hibernate over JDBC 
7.2. Disadvantages of Hibernate 



Spring Framework How to setup JNDI Database Connection pool in Tomcat - Spring Tutorial Example

Setting JNDI Database Connection pool in Spring and Tomcat is pretty easy. Tomcat server documentation gives enough information on how to setup connection pool in Tomcat 5, 6 or 7. Here we will use Tomcat 7 along with spring framework for creating connection pool in Tomcat server and accessing them in Spring using JNDI code. In our last article we have seen how to setup database connection pool in Spring for core Java application which doesn't run on web server or application server and doesn't have managed J2EE container. but if you are developing web application than its better to use server managed connection pool and access them using JNDI. Spring configuration will be generic and just based on JNDI name of Datasource so it will work on any J2EE Server e.g. glassfish, WebLogic, JBoss or WebSphere until JNDI name is same. Tomcat is my favorite web server and I use it a lot on development and its comes integrated with IDE like Eclipse and Netbeans. I am using it for all test and development purpose, Though beware with java.lang.OutOfMemoryError: PermGen space in tomcat,
Read more »

Java J2EE Spring 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.



Spring Framework Oracle ODBC Driver Configuration in Windows XP

Oracle ODBC Driver logoTo start doing JDBC programs in your local machines you should configure the following softwares:

1. Install Java 1.5 or higher version
2. Install Oracle XE (recommended)
3. Set up classpaths for Java and Oracle and ojdbc14 jar file

These three are common things need to be installed in your system to learn JDBC. Make sure Java and Oracle is working fine with out any problems. To run Jdbc programs we should configure a Driver Connection to Java and Oracle to interact each other. For that we have Drivers like a bridge for these two. The Oracle ODBC Driver provides access to Oracle databases for applications written using the ODBC interface.

Setting up an Oracle ODBC Driver and Data Source

Step: #1 In the Windows Start menu , click on the Control Panel icon.

Oracle ODBC Driver Configuration_001
 Step: #2 If you are able to see the 'Performance and Maintenance' icon click on it other wise click on 'Administrative Tools' icon.


  Step: #3 In Administrative Tools you can find Data Sources (ODBC) icon to setup. Click on it to open
Oracle ODBC Driver Configuration_004
  Step: #4 You can see a window named 'Create New Data Source' with list of drives, in that Select Oracle in XE driver then click Finish button.
Oracle ODBC Driver Configuration_005

Step: #5 In the ‘Oracle ODBC Driver Configuration’ dialog, enter the details of your data source name and UserID of your Database as by default 'system' or 'SYSTEM' . Then click on Ok.

Oracle ODBC Driver Configuration_006
Step: #6 Click ‘Test Connection’ to ensure your settings are all correct.When prompted, enter the database login credentials.
Click OK to complete the Setting up Configuring Oracle ODBC Data Source Name.
Oracle ODBC Driver Configuration_008


Java J2EE Spring JDBC - CallableStatement

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 CallableStatement methods to call stored procedures

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

        --->Invoke the Connection.prepareCall method to create a CallableStatement object.
        --->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. See Retrieve 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 the CallableStatement 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.

        Java J2EE Spring 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);

        Spring Framework Top 10 JDBC Interview questions answers for Java programmer

        JDBC Interview Question and Answer
        JDBC Questions are integral part of any Java interview,  I have not seen any Java Interview which is completed without asking single JDBC Interview question, there are always at least one or two question from JDBC API. Some of the popular questions like Why you should use PreparedStatement in Java,  Difference between PreparedStatement and CallableStatement in Java and few questions is related to improving performance of JDBC layer by applying some JDBC performance tips. In this article I have summarized few frequently asked questions in JDBC, they ranges from easy to difficult and beginner to advanced. Questions like distributed transaction management and 2 phase commitis tough to answer until you have real experience but mostly asked in various J2EE interviews. This is not an extensive list of JDBC question answers but practicing or revising this question before going to any Java interview certainly helps.
        Read more »

        Spring Framework JDBC Interview Questions and Answers

        The JDBC questions and answers covered here are an extension to the frequently asked questions covered in "Java/J2EE Job Interview Companion" book. The questions discussed below are generally asked in online JEE technical tests.

        Q. What will be the out put in the following scenario where the table "Course" has the following records



        and the code that is used to access the database is as follows.


            public void executeSelectQuery(Connection con) {
        PreparedStatement ps = null;

        try {
        ps = con.prepareStatement("SELECT COURSE_ID, NAME, COURSE FROM COURSE");
        ResultSet rs = ps.executeQuery(); // read from database

        rs.absolute(0); //moves the cursor to the given row number

        rs.relative(2); //moves the cursor by 2 rows


        while(rs.next()){
        Integer id = rs.getInt("COURSE_ID");
        String name = rs.getString("NAME");
        String course = rs.getString("COURSE");
        System.out.println("id:" + id + ", name:" + name + ", course:" + course);
        }

        }
        catch (Exception e) {
        System.out.println("ERROR executing query: ");
        e.printStackTrace();
        }
        finally{
        try {
        ps.close();
        } catch (SQLException e) {
        e.printStackTrace();
        }
        }
        }





        A. The above code should thrown an exception "java.sql.SQLFeatureNotSupportedException: feature not supported".

        The cause for this exception is in line where you prepare a statement. You are basically creating a cursor here.

        ps = con.prepareStatement("SELECT COURSE_ID, NAME, COURSE  FROM COURSE");

        The above method by default values for the resultSetType and resultSetConcurrency.  So, the above line is equivalent to

        ps = con.prepareStatement("SELECT COURSE_ID, NAME, COURSE  FROM COURSE", 
        ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY );


        The JDBC API definitions for the  resultSetType and resultSetConcurrency are as follows

        resultSetType 
        • TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward only, from before the first row to after the last row. The rows contained in the result set depend on how the underlying database generates the results. That is, it contains the rows that satisfy the query at either the time the query is executed or as the rows are retrieved.
        • TYPE_SCROLL_INSENSITIVE: The result can be scrolled; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. The result set is insensitive to changes made to the underlying data source while it is open. It contains the rows that satisfy the query at either the time the query is executed or as the rows are retrieved.
        • TYPE_SCROLL_SENSITIVE: The result can be scrolled; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. The result set reflects changes made to the underlying data source while the result set remains open.
        resultSetConcurrency 
        • CONCUR_READ_ONLY: The ResultSet object cannot be updated using the ResultSet interface.
        • CONCUR_UPDATABLE: The ResultSet object can be updated using the ResultSet interface.

        Q. What will be the output for the following code snippet for the same "Course" table?

        public void executeSelectQuery(Connection con) {
        PreparedStatement ps = null;

        try {
        ps = con.prepareStatement("SELECT COURSE_ID, NAME, COURSE FROM COURSE", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
        ResultSet rs = ps.executeQuery(); // read from database

        rs.absolute(0); //moves the cursor to the given row number

        rs.relative(2); //moves the cursor by 2 rows


        while(rs.next()){
        Integer id = rs.getInt("COURSE_ID");
        String name = rs.getString("NAME");
        String course = rs.getString("COURSE");
        System.out.println("id:" + id + ", name:" + name + ", course:" + course);
        }

        }
        catch (Exception e) {
        System.out.println("ERROR executing query: ");
        e.printStackTrace();
        }
        finally{
        try {
        ps.close();
        } catch (SQLException e) {
        e.printStackTrace();
        }
        }
        }


        AResultSet.TYPE_SCROLL_INSENSITIVE type will allow the cursor to scroll forward or backward.

        The output will be

        id:3, name:paul, course:JSF
        id:4, name:jonathan, course:Hibernate
        id:5, name:james, course:Spring
        id:6, name:Lewis, course:JDBC

        The cursor will scroll to the first record when rs.absolute(0); is executed. It will scroll another 2 records when  rs.relative(2); is executed. When it gets to the while(rs.next()){ ...} loop it will start printing from third record onwards. You can practice different scenarios with the JDBC Tutorial.


        Q. What is RowSet? What is the difference between RowSet and ResultSet? What are the advantages of using RowSet over ResultSet?

        ARowSets are a JDBC 2.0 extension to the java.sql.ResultSet interface. Guess what, it makes life a lot easier for all JDBC programmers. No more Connection objects, statement objects, just a single RowSet will do everything for you. RowSet object follows the JavaBeans model for properties and event notification, it is a JavaBeans component that can be combined with other components in an application.

        The ResultSet has an 'open connection' to the database whereas a RowSet works in a 'disconnected' fashion. It has the following advantages over a ResultSet.

        • Since a RowSet works in a disconnected mode, especially for "read-only" queries, it would have better performance in a highly concurrent system.
        • Rowsets have many different implementations to fill different needs. These implementations fall into two broad categories, rowsets that are connected and those that are disconnected. 
        • Rowsets make it easy to send tabular data over a network. They can also be used to provide scrollable result sets or updatable result sets in special cases when the underlying JDBC driver does not support them.

        RowSet disadvantages.
        • Rowset keeps all the data from the query result in memory. This is very in-efficient for queries that return huge data.

        There are 3 types of RowSets. The JdbcRowset 

        JdbcRowSet is a connected type of rowset as it maintains a connection to the data source using a JDBC driver

        JdbcRowSet jdbcRowSet = new JdbcRowSetImpl();
        jdbcRowSet.setCommand("SELECT * FROM Course);
        jdbcRowSet.setURL("jdbc:hsqldb:hsql://localhost/mytestdb");
        jdbcRowSet.setUsername("sa");
        jdbcRowSet.setPassword("pwd");
        jdbcRowSet.execute();

        CachedRowSet and WebRoeSet are disconnected types of rowsets as they are connected to the data source only when reading data from it or writing data to it.

        ResultSet rs = stmt.executeQuery("SELECT * FROM Course");
        CachedRowSet crset = new CachedRowSetImpl();
        crset.populate(rs);


        WebRowSet wrs = new WebRowSetImpl();
        wrs.populate(rs);
        wrs.absolute(2)
        wrs.updateString(1, "JNDI");


        Q. What is Metadata and why should you use it?
        A. JDBC API has 2 Metadata interfaces -- DatabaseMetaData & ResultSetMetaData. The  meta data means data about data, and provides comprehensive information about the database as a whole. The implementation for this interface is implemented by database driver vendors to let users know the capabilities of a Database.

        ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");  
        ResultSetMetaData resultSetMeta = rs.getMetaData();
        int numberOfColumns = resultSetMeta.getColumnCount();
        boolean b = resultSetMeta.isSearchable(3);


        Q. What are database warnings and why do you need them?
        A. Warnings are issued by a database to inform user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. Warnings are silently chained to the object. You need warnings for the reporting purpose. Warnings may be retrieved from Connection, Statement, and ResultSet objects.

        SQLWarning warning = conn.getWarnings();  
        QLWarning nextWarning = warning.getNextWarning();
        conn.clearWarnings();
        ...
        stmt.getWarnings();
        stmt.clearWarnings();
        ...
        rs.getWarnings();
        ...


        Spring Framework Spring Framework Tutorial - How to call Stored Procedures from Java using IN and OUT parameter example

        Spring Framework provides excellent support to call stored procedures from Java application. In fact there are multiple ways to call stored procedure in Spring Framework, e.g. you can use one of the query() method from JdbcTemplate to call stored procedures, or you can extend abstract class StoredProcedure to call stored procedures from Java. In this Java Spring tutorial, we will see second approach to call stored procedure. It's more object oriented, but same time requires more coding. StoredProcedure class allows you to declare IN and OUT parameters and call stored procedure using its various execute() method, which has protected access and can only be called from sub class. I personally prefer to implement StoredProcedure class as Inner class, if its tied up with one of DAO Object, e.g. in this case it nicely fit inside EmployeeDAO. Then you can provide convenient method to wrap stored procedure calls. In order to demonstrate, how to call stored procedures from spring based application, we will first create a simple stored proc using MySQL database, as shown below.
        Read more »

        Spring Framework JDBC Batch INSERT and UPDATE example in Java with PreparedStatement

        JDBC API in Java allows program to batch insert and update data into database, which tends to provide better performance by simple virtue of fact that it reduce lot of database round-trip which eventually improves overall performance. In fact it’s one of JDBC best practices to insert and update data in batches. For those who doesn’t know what is batch insert and update, Java provides several ways to execute SQL queries, one of them is JDBC batch insert and update, on which instead of executing sql query one by one using either Statement or PreparedSatement, you execute query in batch and send a batch of query to database for execution instead of single query. Since multiple queries are combined into batch and one batch is sent to database instead of individual queries, it reduce database round trip by factor of batch size. Batch size can be anything but needs to be decided carefully. JDBC specification supports upto 100 but individual database e.g. Oracle, MySQL, Sybase or SQL Server has there own limit on maximum batch size, , normal jdbc batch size ranges from 50 to 100. JDBC API provides addBatch() method to add queries into batch and than later execute them using executeBatch() method. Both Statement and PreparedStatement can be used to execute batch queries in Java. By the way batch insert and update also provide performance boost to Data access Object or DAO layer,  as discussed in our last post 4 ways to improve Performance of JDBC applications.
        Read more »

        Labels

        .equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()