Google News
logo
JDBC Interview Questions
JDBC(Java Database Connectivity) is a Java Application Programming Interface(API), which is helpful in interaction with the database to retrieve, manipulate and process the data using SQL. It will make use of JDBC drivers for connecting with the database. By using JDBC, we can access tabular data stored in various types of relational databases such as Oracle, MySQL, MS Access, etc.
JDBC Driver is a software component that enables Java application to interact with the database.

There are 4 types of JDBC drivers :
 
JDBC-ODBC bridge driver : The JDBC-ODBC bridge driver uses the ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of the thin driver. It is easy to use and can be easily connected to any database.

Native-API driver (partially java driver) : The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in Java. Its performance is better than JDBC-ODBC bridge driver. However, the native driver must be installed on each client machine.

Network Protocol driver (fully java driver) : The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is entirely written in Java. There is no requirement of the client-side library because of the application server that can perform many tasks like auditing, load balancing, logging, etc.

Thin driver (fully java driver) : The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as the thin driver. It is entirely written in Java language. Its performance is better than all other drivers however these drivers depend upon the database.
JDBC DriverManager is a static class in Java, through which we manage the set of JDBC drivers that are available for an application to use.
Multiple JDBC drivers can be used concurrently by an application, if necessary. By using a Uniform Resource Locator(URL), each application specifies a JDBC driver.

When we load the JDBC Driver class into an application, it registers itself to the DriverManager by using Class.forName() or DriverManager.registerDriver(). To check this, you can have a look into the source code of JDBC Driver classes. After this, when we call DriverManager.getConnection() method by passing the details regarding database configuration, DriverManager will make use of registered drivers to obtain the connection and return it to the caller program.
JDBC supports 2 kinds of processing models to access the DB.
 
* Two-tier Architecture : Here Java programs explicitly connect with DB. We don’t need any mediator like applications server to connect with DB except the JDBC driver. It is also known as a client-server architecture.

* Three-tier Architecture : It is totally inverse of two-tier architecture. There will be no explicit communication between the JDBC driver or Java program and Database. An application server is used as a mediator between them. Java program will send the request to an application server, and the server will send it and receive the response to/ from DB.
* BLOB data type is used to store the image in the database. We can also store videos and audio by using the BLOB data type. It stores the binary type of data.

* CLOB data type is used to store the file in the database. It stores the character type of data.
By using setNull() method of PreparedStatement interface, we can set the null value to an index. The syntax of the method is given below.
 
void setNull(int parameterIndex, int sqlType) throws SQLException

(OR)

We can use PreparedStatement setNull() method to bind the null variable to a parameter. The setNull method takes index and SQL Types as argument, for example :

ps.setNull(10, java.sql.Types.INTEGER);

* The PreparedStatement performs faster as compare to Statement because the Statement needs to be compiled everytime we run the code whereas the PreparedStatement compiled once and then execute only on runtime.

* PreparedStatement can execute Parameterized query whereas Statement can only run static queries.

* The query used in PreparedStatement is appeared to be similar every time. Therefore, the database can reuse the previous access plan whereas, Statement inline the parameters into the String, therefore, the query doesn't appear to be same everytime which prevents cache reusage.
* DatabaseMetaData is an interface that provides methods to obtain information about the database.

* We can use this for getting database-related informations, such as database name, database version, driver name, the total number of tables or views, etc.
There are 4 major components that are available in JDBC.
 
* JDBC API
* JDBC Driver Manager
* JDBC Test Suite
* JDBC – ODBC Bridge
There are 6 basic steps to connect with DB in Java. These are enlisted below :
 
* Import package
* Load driver
* Establish connection
* Creation and execution of the statement
* Retrieve results
* Close connection
There are three(3) types of ResultSet is available. If we do not declare any ResultSet that means we are calling TYPE_FORWARD_ONLY
 
TYPE_FORWARD_ONLY : cursor can move only forward.
TYPE_SCROLL_INSENSITIVE : cursor can move forward and backward but not sensitive.
TYPE_SCROLL_SENSITIVE : cursor can move forward and backward, but it is sensitive.
execute() method : This method is used to execute SQL DDL statements, it returns a boolean value specifying weather the ResultSet object can be retrieved.
 
executeQuery() : This method is used to execute statements that returns tabular data (example select). It returns an object of the class ResultSet.
 
executeUpdate() : This method is used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected.

(Or)

execute() method : it can be used for any kind of SQL Query.
 
executeQuery() : it can be used for select query.
 
executeUpdate() : it can be used to change/update table.
We can use DatabaseMetaData object to get the database server details. When the database connection is created successfully, we can get the meta data object by calling getMetaData() method. There are so many methods in DatabaseMetaData that we can use to get the database product name, it’s version and configuration details.
DatabaseMetaData metaData = con.getMetaData();
String dbProduct = metaData.getDatabaseProductName();

 

We can execute the SQL Stored procedures through the CallableStatement interface. The CallableStatement object can be created using the prepareCall() method of the Connection interface.
This interface gives more information about ResultSet. Each ResultSet object has been associated with one ResultSetMetaData object.
 
This object will have the details of the properties of the columns like datatype of the column, column name, the number of columns in that table, table name, schema name, etc., getMetaData() method of ResultSet object is used to create the ResultSetMetaData object.
 
Syntax :
PreparedStatement pstmntobj = conn.prepareStatement(insert_query);
ResultSet resultsetobj = pstmntobj.executeQuery(“Select * from EMPLOYEE”);
ResultSetMetaData rsmd obj= resultsetobj.getMetaData();

 

Commit() method : We have the commit() method in Java to commit the data. Once the SQL execution is done, we can call the commit method.
 
Syntax : connectionobj.commit();
 
Rollback() method : We have the rollback() method in Java to rollback the data. Rollback means to undo the changes. If any of the SQL statements are failed, we can call the rollback method to undo the changes.
 
Syntax : connectionobj.rollback();

Savepoint is used to create checkpoints in a transaction, and it allows us to perform a rollback to the specific savepoint. Once the transaction is committed or rolled backed, the savepoint that has been created for a transaction will be automatically destroyed and becomes invalid.
 
Methods for Savepoint :
 
setSavepoint() method : It is used to create Savepoint, we can use the rollback() method to undo all the changes till the savepoint.
releaseSavepoint() method: It is used to remove the given savepoint.
setMaxRows(int) : Defines how many rows a resultset can contain at a time
 
SetFetchSize(int) : Defines the number of rows that will be read from the database.
Two types of locking are available in JDBC by which we can handle more than one user.
 
If two users are viewing the same record, then no locking is done. If one user is updating a record and the second user is also updating the same record.  At that time, we are going to use locking.
 
* Optimistic Locking : it will lock the record only when we are going to “update.”
* Pessimistic Locking : it will lock the record from the “select” to view, update and commit time.
Sometimes a table can have auto generated keys used to insert the unique column value for primary key. We can use Statement getGeneratedKeys() method to get the value of this auto generated key.
JDBC DataSource is the interface defined in javax.sql package and it is more powerful that DriverManager for database connections. We can use DataSource to create the database connection and Driver implementation classes does the actual work for getting connection. Apart from getting Database connection, DataSource provides some additional features such as:
 
* Caching of PreparedStatement for faster processing
* Connection timeout settings
* Logging features
* ResultSet maximum size threshold
* Connection Pooling in servlet container using JNDI support..
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested.
The JDBC 3.0 API  It contains many features, including scrollable result sets and the SQL:1999 data types.
 
JDBC (Java Database Connectivity) is the standard for communication between a Java application and a relational database. The JDBC API is released in two versions; JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released with Java platform 2 in packages java.sql and javax.sql). It is a simple and powerful largely database-independent way of extracting and inserting data to or from any database.
The JDBC™ 4.3 API includes both the java.sql package, referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional Package API. This complete JDBC API is included in the Java™ Standard Edition (Java SE™), version 7. The javax.sql package extends the functionality of the JDBC API from a client-side API to a server-side API, and it is an essential part of the Java™ Enterprise Edition (Java EE™) technology.
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.
 
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.
Data Manipulation Language (DDL) this portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The DML deals with the SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.
 
Data Definition Language (DDL) this portion of the SQL standard is concerned with the creation, deletion and modification of database objects like tables, indexes and views. The core verbs for DDL are CREATE, ALTER and DROP. While most DBMS engines allow DDL to be used dynamically, it is often not supported in transactions.
The transaction isolation level is a value that determines the level at which inconsistent data is allowed in a transaction, that is, the degree of isolation of one transaction from another. A higher level of isolation improves data accuracy, but it may decrease the number of concurrent transactions. On the other hand, a lower level of isolation allows for more concurrent transactions, but reduces the accuracy of the data.
 
When we use transactions in JDBC to ensure data integrity, the DBMS uses locks to block the access of other accesses to the data involved in the transaction. Such locks are necessary to prevent dirty reading (Dirty Read), non-repeatable reading (Non-Repeatable Read) and phantom reading (Phantom-Read).
 
The isolation level of the JDBC transaction used by the DBMS for the locking mechanism can be set using the setTransactionIsolation () method . You can get information about the level of isolation used by the Connection getTransactionIsolation () method.
Character Large OBjects (CLOBs) is a data type (internal character object) used to store large objects. When selecting a value of any LOB type, a pointer is returned via the SELECT statement, and not the value itself; In addition, LOB types can be external. This data type is suitable for storing textual information that may fall outside the normal VARCHAR data type (upper limit of 32 KB).
 
An internal blob (BLOB) is a large binary object that can contain a variable amount of data. This data type can store data larger than VARBINARY (32K limit). A type of data intended primarily for storing images, audio and video, as well as compiled program code.
java.util.Date contains information about the date and time, whereas java.sql.Date contains information about the date, but has no information about the time. If you need to store time information in the database, it is desirable to use the Timestamp or DateTime fields.
 
Java.util.Date is the main universal object. It simply stores the date (as long).
 
java.sql.Date extends java.util.Date and adds the following functionality :
 
1) toString prints the date as “yyyy-mm-dd”, rather than as a specific locale of the string (locale).
 
2) Added the valueOf method to read the “yyyy-mm-dd” format strings and further parse it into the sql.Date object.
SQLWarning is a subclass of SQLException that we can get by calling the getWarnings () method on Connection , Statement , ResultSet  objects  . SQL Warnings does not stop the execution of the query, but displays warning messages for the user.
The getClob() method of PreparedStatement is used to get file information from the database. Let's see the table structure of the example to retrieve the file.
CREATE TABLE  "FILETABLE"   
   (    "ID" NUMBER,   
    "NAME" CLOB  
   )  
The example to retrieve the file from the Oracle database is given below :
import java.io.*;  
import java.sql.*;  
  
public class RetrieveFile {  
public static void main(String[] args) {  
try{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
              
PreparedStatement ps=con.prepareStatement("select * from filetable");  
ResultSet rs=ps.executeQuery();  
rs.next();//now on 1st row  
              
Clob c=rs.getClob(2);  
Reader r=c.getCharacterStream();              
              
FileWriter fw=new FileWriter("d:\\retrivefile.txt");  
              
int i;  
while((i=r.read())!=-1)  
fw.write((char)i);  
              
fw.close();  
con.close();  
              
System.out.println("success");  
}catch (Exception e) {e.printStackTrace();  }  
}  
}  

 

Statements are useful for sending SQL commands to the database and receiving data from the database. There are three types of statements in JDBC. They are :
 
Statement : It is the factory for ResultSet. It is used for general-purpose access to the database by executing the static SQL query at runtime.
Statement st = conn.createStatement( );
ResultSet rs = st.executeQuery();
PreparedStatement : It is used when we need to give input data to the query at runtime and also if we want to execute SQL statements repeatedly. It is more efficient than a statement because it involves the pre-compilation of SQL.
String SQL = "Update item SET limit = ? WHERE itemType = ?";
 PreparedStatement  ps = conn.prepareStatement(SQL);
 ResultSet rs = ps.executeQuery();
CallableStatement : It is used to call stored procedures on the database. It is capable of accepting runtime parameters.
CallableStatement cs = con.prepareCall("{call SHOW_CUSTOMERS}");
ResultSet rs = cs.executeQuery();

 

* Batch processing is the process of executing multiple SQL statements in one transaction. For example, consider the case of loading data from CSV(Comma-Separated Values) files to relational database tables. Instead of using Statement or PreparedStatement, we can use Batch processing which executes the bulk of queries in a single go for a database.

* Advantages of Batch processing :
   * It will reduce the communication time and improves performance.
   * Batch processing makes it easier to process a huge amount of data and consistency of data is also maintained.
   * It is much faster than executing a single statement at a time because of the fewer number of database calls.

* How to perform Batch processing?

To perform Batch processing, addBatch() and executeBatch() methods are used. These 2 methods are available in the Statement and PreparedStatement classes of JDBC API.
No suitable driver” error occurs during a call to the DriverManager.getConnection() method, because of the following reasons :
 
* Unable to load the appropriate JDBC drivers before calling the getConnection() method.
* It can specify an invalid or wrong JDBC URL, which cannot be recognized by the JDBC driver.
* This error may occur when one or more shared libraries required by the bridge cannot be loaded.
Stored procedures are a set of SQL queries that are compiled in the database and will be executed from JDBC API. For executing Stored procedures in the database, JDBC CallableStatement can be used. The syntax for initializing a CallableStatement is:
CallableStatement cs = con.prepareCall("{call insertEmployee(?,?,?,?,?)}");
stmt.setInt(1, id);
stmt.setString(2, name);
stmt.setString(3, role);
stmt.setString(4, address);
stmt.setString(5, salary);
//registering the OUT parameter before calling the stored procedure
cs.registerOutParameter(5, java.sql.Types.VARCHAR);
            
cs.executeUpdate();

We must register the OUT parameters before executing the CallableStatement.

8 packages are used in JDBC :
 
* sql.Driver
* Connection
* Statement
* PreparedStatement
* CallableStatement
* ResultSet
* ResultSetMetaData
* DatabaseMetaData
Following methods helps you to update result set : 
 
* updateRow()
* deleteRow()
* refreshRow()
* insertRow()
* cancelRowUpdates()
If you use DataSource to get the Database connection, usually the code to get the connection is tightly coupled with the Driver specific DataSource implementation. Also most of the code is boiler-plate code except the choice of the DataSource implementation class.
 
Apache DBCP helps us in getting rid of these issues by providing DataSource implementation that works as an abstraction layer between our program and different JDBC drivers. Apache DBCP library depends on Commons Pool library, so make sure they both are in the build path.
When we work in distributed systems where multiple databases are involved, we are required to use 2 phase commit protocol. 2 phase commit protocol is an atomic commitment protocol for distributed systems. In the first phase, the transaction manager sends commit-request to all the transaction resources. If all the transaction resources are OK, the transaction manager commits the transaction changes for all the resources. If any of the transaction resources responds as Abort, then the transaction manager can rollback all the transaction changes.
If Oracle Stored Procedure has IN/OUT parameters as DB Objects then we need to create an Object array of the same size in the program and then use it to create Oracle STRUCT object. Then we can set this STRUCT object for the database object by calling setSTRUCT() method and work with it.
JDBC driver performance will depend on a number of issues :
 
* The quality of the driver code,
* The size of the driver code,
* The database server and its load,
* Network topology,
* The number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
There are two ways of connecting to a database on the server side.
 
The hard way : Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.

The easy way : Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
Following are the tasks of JDBC : 
 
* Load the JDBC drivers
* Register the drivers
* Specify a database
* Open a connection to database
* Submit a query to database
* Gets the results.
Connection con = null;
Statement st = null;
// Obtain connection here
st = con.createStatement();
ResultSet rs = null;
rs = st.executeQuery("SELECT * FROM users");
int recordsUpdated;
recordsUpdated = st.executeUpdate("DELETE FROM users WHERE user_id = 1");