JDBC Interview Questions
What are the types of statements in JDBC?
JDBC API has 3 Interfaces and their key
features of these are as follows:
Statement: which is used to run simple SQL
statements like select and update. Statement interfaces use for general-purpose
access to your database. It is useful when you are using static SQL statements
at runtime. The Statement interface cannot accept parameters.
Prepared Statement: A SQL statement is
pre-compiled and stored in a Prepared Statement object. It is used to run Pre
compiled SQL. This object can then be used to efficiently execute this
statement multiple times. The object of Prepared Statement class can be created
using Connection.prepareStatement() method. This extends Statement interface.
Callable Statement: This interface is
used to execute the stored procedures. This extends Prepared Statement
interface. The object of Callable Statement class can be created using
Connection.prepareCall() method.
What causes No suitable driver error?
"No suitable driver" is occurs
during a call to the DriverManager.getConnection method, may be of any of the
following reason:
- Due
to failing to load the appropriate JDBC drivers before calling the
getConnection method.
- It
can be specifying an invalid JDBC URL, one that is not recognized by JDBC
driver.
- This
error can occur if one or more the shared libraries needed by the bridge
cannot be loaded
What does setAutoCommit do?
setAutoCommit() invoke the commit state query
to the database. To perform batch updation we use the setAutoCommit() which enable
us to execute more than one statement together, which in result minimize the
database call and send all statement in one batch.
setAutoCommit() allowed us to commit the transaction commit state manually the default values of the setAutoCommit() is true.
setAutoCommit() allowed us to commit the transaction commit state manually the default values of the setAutoCommit() is true.
Why Prepared Statements are faster?
Prepared execution is faster than direct
execution for statements executed more than three or four times because the
statement is compiled only once. Prepared statements and JDBC driver are linked
with each other. We can bind drivers with columns by triggering the query into
the database. When we execute Connection.prepareStatement(), all the columns
bindings take place, in oder to reduce the time.
What restrictions are placed on method overriding?
The restriction on method overloading is the
signature of the method.
- The
signature is the number, type, and order of the arguments passed to a
method.
- Overridden
methods must have the same name, argument list, and return type.
- Any
method which has the same name cannot have the same signature.
- They
can have the same return types in the same scope.
- The
compiler uses the signature to detect which overloaded method to refer
when a overloaded method is called.
- If
two methods have the same name and signature the compiler will throw a
runtime error.
What are types of JDBC drivers?
There are four types of drivers defined by
JDBC as follows:
- JDBC/ODBC: These require an ODBC (Open Database
Connectivity) driver for the database to be installed. It is used for
local connection.
- Native
API (partly-Java driver): This
type of driver uses a database API to interact with the database. It also
provides no host redirection.
- Network
Protocol Driver: It makes use of a
middle-tier between the calling program and the database. The client
driver communicates with the net server using a database-independent
protocol and the net server translates this protocol into database calls.
- Native
Protocol Drive: This has a same
configuration as a type 3 driver but uses a wire protocol specific to a
particular vendor and hence can access only that vendor's database.
Is it possible to connect
to multiple databases simultaneously? Using single statement can one update or
extract data from multiple databases?
Yes, it is possible but it depends upon the
capabilities of the specific driver implementation, we can connect to multiple
databases at the same time. We doing following steps:
- Minimum
one driver will be used to handle the commits transaction for multiple
connections.
- To
update and extract data from the different database we use single
statement for this we need special middleware to deal with multiple
databases in a single statement or to effectively treat them as one
database.
What are the differences between setMaxRows(int) and
SetFetchSize(int)?
The difference between setFetchSize and
setMaxRow are:
- setFetchSize(int)
defines the number of rows that will be read from the database when the
ResultSet needs more rows whereas setMaxRows(int) method of the ResultSet
specifies how many rows a ResultSet can contain at a time.
- In
setFetchSize(int), method in the java.sql.Statement interface will set the
'default' value for all the ResultSet derived from that Statement whereas
in setMaxRow(int) default value is 0, i.e. all rows will be included in
the ResultSet.
- the
setMaxRows affects the client side JDBC object while the setFetchSize
affects how the database returns the ResultSet data.
How can I manage special characters when I execute an
INSERT query?
The special characters meaning in SQL can be
preceded with a special escape character in strings, e.g. "\". In
order to specify the escape character used to quote these characters, include
the following syntax on the end of the query:
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}
finds identifier names that begin with an underscore.
{escape 'escape-character'}
For example, the query
SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}
finds identifier names that begin with an underscore.
What is the benefit of having JdbcRowSet implementation?
Why do we need a JdbcRowSet like wrapper around ResultSet?
The JdbcRowSet implementation is a wrapper
around a ResultSet object has following advantages over ResultSet:
- It
makes possible to use the ResultSet object as a JavaBeans component.
- A
JdbcRowSet can be used as a JavaBeans component, thus it 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.
Explain Basic Steps in
writing a Java program using JDBC.
JDBC makes the interaction with RDBMS simple
and intuitive. When a Java application needs to access database :
- Load
the RDBMS specific JDBC driver because this driver actually communicates
with the database.
- Open
the connection to database, for sending SQL statements and get results
back.
- Create
JDBC Statement object containing SQL query.
- Execute
statement which returns result set. ResultSet contains the tuples of
database table as a result of SQL query.
- Process
the result set.
- Close
the connection.
I have the choice of
manipulating database data using a byte[] or a java.sql.Blob. Which has best
performance?
We use java.sql.Blob, because of following
reason:
- It
does not extract any data from the database until we trigger a query to
the databse.
- We
use byte[] for inserting data in the database when data is not upload in
the database till yet.
- java.sql.Blob
is used when extraction of the data is performed.
What are DML and DDL?
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.
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.
How can you load the drivers?
It is very simple and involves just one line
of code to load the driver or drivers we want to use.
For example, We want to use the JDBC-ODBC
Bridge driver, the following code will load it:
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
Driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverHELLO, you would load the driver with the following line of code:
Class.forName(”jdbc.DriverHELLO”);
Driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverHELLO, you would load the driver with the following line of code:
Class.forName(”jdbc.DriverHELLO”);
How do I insert an image file (or other raw data) into a
database?
All raw data types should be read and
uploaded to the database as an array of bytes, byte[].
- Originating
from a binary file.
- Read
all data from the file using a FileInputStream.
- Create
a byte array from the read data.
- Use
method setBytes(int index, byte[] data); of java.sql.PreparedStatement to
upload the data.
java.sql: java.sql is an
API to access and process the data stored in a database, typically a
relational database using the java. Different drivers can be installed
dynamically for the access of va
Opening
a database connection: The database connection should be established after
registering the drivers. The getConnection is used to open a database
connection. The following code snippet illustrates this:...............
The following illustrates
with examples, to send SQL statements to databases for execution: The SQL
statements are to be created as objects. These objects are to be assigned to
Statement reference.....
...........
In typical database transactions, one
transaction reads changes the value while the other reads the value before
committing or rolling back by the first transaction...
...............
Cold
backup is a recovery technique, in which the files must be backed up before
the database is restarted at the same time.....
......
Distributed transactions are performed by
relational databases. To ensure each and every transaction to perform in an
orderly manner, a process is implemented..........
........
Resultset contains
results of the SQL query. There are 3 basic types of resultset. Forward-only:
As name suggest, this type can only move forward and are
non-scrollable...
....
Transaction
Isolation levels is used to implement locking. They decide how one process
isolated from other is. We have four Transaction Isolation Levels..
.......
There
are two kinds of locking available in JDBC. Optimistic Locking, Pessimistic
Locking...........
1. Discuss the significances of JDBC.
The
significances are given below:
• JDBC is the acronym stands for Java Database Connectivity. • Java Database Connectivity (JDBC) is a standard Java API . • It's purpose is to interact with the relational databases in Java. • JDBC is having a set of classes & interfaces which can be used from any Java application. • By using the Database Specific JDBC drivers, it interacts with a database without the applications of RDBMS.
Name
the new features added in JDBC 4.0.
The
major features introduced in JDBC 4.0 are :
• Auto-loading by JDBC driver class. • Enhanced Connection management • RowId SQL enabled. • DataSet implemented by SQL by using Annotations • Enhancements of SQL exception handling • Supporting SQL XML files.
.
How do Java applications access the database using JDBC?
Java
applications access the database using JDBC by :
• Communicating with the database for Loading the RDBMS specific JDBC driver • Opening the connection with database • Sending the SQL statements and get the results back. • Creating JDBC Statement object which contains SQL query. • Executing statement to return the resultset(s) containing the tuples of database table which is a result of SQL query. • Processing the result set. • Closing the connection.
.
Briefly tell about the JDBC Architecture.
The
JDBC Architecture consists of two layers:
1.The JDBC API 2.The JDBC Driver API • The JDBC API provides the application-JDBC Manager connection. • The JDBC Driver API supports the JDBC Manager-to-Driver Connection. • The JDBC API interacts with a driver manager, database-specific driver for providing transparent connectivity for the heterogeneous databases. • The JDBC driver manager authenticates that the correct driver has been used to access each data source. • The driver manager supports multiple concurrent drivers connected to the multiple heterogeneous databases.
.Explain
the life cycle of JDBC.
The
life cycle for a servlet comprises of the following phases:
• DriverManager : for managing a list of database drivers. • Driver : for communicating with the database. • Connection : for interfacing with all the methods for connecting a database. • Statement : for encapsulating an SQL statement for passing to the database which had been parsed, compiled, planned and executed. • ResultSet: for representing a set of rows retrieved for the query execution.
Describe
how the JDBC application works.
A
JDBC application may be divided into two layers:
• Driver layer • Application layer • The Driver layer consists of DriverManager class & the JDBC drivers. • The Application layer begins after putting a request to the DriverManager for the connection. • An appropriate driver is chosen and used for establishing the connection. • This connection is linked to the application layer. • The application needs the connection for creating the Statement kind of objects by which the results are obtained.
.
How a database driver can be loaded with JDBC 4.0 / Java 6?
•
By providing the JAR file , the driver must be properly configured.
• The JAR file is placed in the classpath. • It is not necessary to explicitly load the JDBC drivers by using the code like Class.forName() to register in the JDBC driver. • The DriverManager class looks after this, via locating a suitable driver at the time when the DriverManager.getConnection() method is called. • This feature provides backward-compatibility, so no change is needed in the existing JDBC code.
.
What does the JDBC Driver interface do?
•
The JDBC Driver interface provides vendor-specific customized implementations
of the abstract classes.
• It is provided normally by the JDBC API. • For each vendor the driver provides implementations of the java.sql.Connection, , PreparedStatement, Driver,Statement, ResultSet and CallableStatement.
What
is represented by the connection object?
•
The connection object represents the communication context.
• All the communication with the database is executed via the connection objects only. • Connection objects are used as the main linking elements.
What
is a Statement ?
•
The Statement acts just like a vehicle via which SQL commands are sent.
• By the connection objects, we create the Statement kind of objects. Statement stmt = conn.createStatement(); • This method returns the object, which implements the Statement interface.
.Define
PreparedStatement.
•
A Preparedstatement is an SQL statement which is precompiled by the database.
• By precompilation, the prepared statements improve the performance of the SQL commands that are executed multiple times (given that the database supports prepared statements). • After compilation, prepared statements may be customized before every execution by the alteration of predefined SQL parameters. Code: PreparedStatement pstmt = conn.prepareStatement("UPDATE data= ? WHERE vl = ?"); pstmt.setBigDecimal(1, 1200.00); pstmt.setInt(2, 192);
Differentiate between a Statement and a
PreparedStatement.
•
A standard Statement is used for creating a Java representation for a literal
SQL statement and for executing it on the database.
• A PreparedStatement is a precompiled Statement. • A Statement has to verify its metadata in the database every time. • But ,the prepared statement has to verify its metadata in the database only once. • If we execute the SQL statement, it will go to the STATEMENT. • But, if we want to execute a single SQL statement for the multiple number of times, it’ll go to the PreparedStatement.
What
is the function of setAutoCommit?
•
When a connection is created, it is in auto-commit mode.
• This means that each individual SQL statement is to be treated as a single transaction . • The setAutoCommit will be automatically committed just after getting executed. • The way by which two or more statements are clubbed into a transaction to disable the auto-commit mode is : con.setAutoCommit (false); • Once auto-commit mode is disabled, no SQL statements will be committed until we call the method ‘commit’ explicitly. Code : con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEE SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);
How do we call a stored procedure from JDBC?
•
The foremost step is to create a CallableStatement object.
• With the Statement and PreparedStatement object ,it is done with an open Connection object. • A CallableStatement object contains a call to a stored procedure. Code: CallableStatement cs = con.prepareCall("{call SHOW_Sales}"); ResultSet rs = cs.executeQuery();
What
is SQLWarning and discuss the procedure of retrieving warnings?
•
SQLWarning objects, a subclass of SQLException is responsible for the
database access warnings.
• Warnings will not stop the execution of an specific application, as exceptions do. • It simply alerts the user that something did not happen as planned. • A warning may be reported on the Connection object, the Statement object (including PreparedStatement and CallableStatement objects) or on the ResultSet object. • Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object: Code : SQLWarning waring = stmt.getWarnings(); if (warning != null) { System.out.println("n---Warning---n"); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.println("Vendor error code: "); System.out.println(warning.getErrorCode()); System.out.println(""); warning = warning.getNextWarning(); } }
Explain the types of JDBC Drivers and name
them.
The
4 types of JDBC Drivers are:
• Pure Java Driver JDBC Net • Bridge Driver JDBC-ODBC • Network protocol Driver • Partly Java Driver Native API
How
can we move the cursor in a scrollable result set?
•
The new features added in the JDBC 2.0 API are able to move a resultset’s
cursor backward & forward also.
• There are some methods that let you direct the cursor to a particular row and checking the position of the cursor. Code : Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, Sale _COFFEE”); • Three constants can be added to the ResultSet API for indicating the kind of the ResultSet object. The constants are: - TYPE_FORWARD_ONLY - TYPE_SCROLL_INSENSITIVE - TYPE_SCROLL_SENSITIVE. • The ResultSet constants for specifying whether a resultset is read-only or updatable are: - CONCUR_READ_ONLY - CONCUR_UPDATABLE.
18. How do we load the drivers?
•
To Load the driver or drivers we need to use a very simple one line of
code.
• If we want to use the JDBC/ODBC Bridge driver, the following code will load it: Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); • The driver documentation gives the class name to use. • For example, if the class name is jdbc.DriverXYZ, we can load the driver using the below line of code: Code: Class.forName(”jdbc.DriverXYZ”);
19. What Class.forName does, while loading
the drivers?
•
It is used for creating an instance of a driver
• It is used for registering with theDriverManager. • When we have loaded a driver, it connects with the DBMS.
.
How can you make a connection?
•
To establish a connection we need to have an appropriate driver, connected to
the DBMS.
• The below line of code illustrates the idea: Code: String url = “jdbc:odbc: rima”; Connection con = DriverManager.getConnection(url, “rima”, “J8?);
1. What are the factors that the JDBC
driver performance depends on?
The
JDBC driver performance depends on:
• The driver code quality • The driver code size • The database server & its load capability • The network topology • The number of times the request is being translated to a different API.
2. How do I find whether a parameter exists
in the request object?
•
The following code implies it
boolean hasFo = !(request.getParameter("fo") == null request.getParameter("fo").equals("")); |
Difference between SQL Date and java.util.Date
in Java
This
is one of JDBC Questions which I like to ask, because knowing how to correctly
store and retrieve date in a database is often confusing for new developers and
its very critical for any application. Main difference between SQL data i.e. java.sql.Dateand util date i.e. java.util.Date is that SQL Date only contains date
part and not time part but util date contains both date and time part. See SQL
Date vs Util Date in Java for
more differences between them.
What
is benefit of using PreparedStatement in Java
Another
wonderful JDBC interview question which is very popular on telephonic as well
as on early round of Java Interviews. There are several benefits of using PreparedStatement while querying database from Java
program e.g. better performance and prevents from SQL Injection. I suggest to
read Why
use PreparedStatement in Java for
more benefits and details on JDBC PreparedStatement.
What is JDBC database Connection Pool? How to
setup in Java?
Answer
: I have always seen at least one question related to database connection pool
in JDBC Interview e.g. benefit of using JDBC Connection pool. Well JDBC
connection pool maintains pool of JDBC connection which is used by application
to query database. Since JDBC connection are expensive it take time to create
them which can slow response time of server if created during request time.
Creating them on application start-up and reusing them result in better
performance. See How
to setup JDBC Connection Pool in Java using Spring for more details on JDBC connection
pool and benefits it offer.
What
is difference between type 2 and type 4 JDBC drivers in Java
This
JDBC Interview question is as old as Vector
vs ArrayList or Hashtable vs HashMap. I remember questions
about JDBC ODBC drivers asked during almost every fresher level
interview. Key difference
between type 2 and type 4 JDBC driver is that you just need to include JAR file
of JDBC driver in your classpath to connect database. See this link for more difference
between type 2 and type 4 JDBC drivers.
What is difference between java.sql.Time and
java.sql.TimeStamp in Java
Answer
: This JDBC questions is similar to earlier JDBC interview question java.sql.Date vs java.util.Date. Main difference is
that java.sql.Time class doesn't contain any date
information on it while java.sql.TimeStamp contains date information. See4
difference between Time and Timestamp in Java JDBC for more differences.
What
happens if we call resultSet.getInt(0) when Select query result just have one
column of integer type?
t his
is one of the tricky
Java question which
comes from JDBC. you may think that it will return first column as integer from
Query result set but unfortunately it doesn't. It throws InvalidColumnIndexException in JDBC because index for getXXX() orsetXXX() in JDBC starts with 1. See How
to fix InvalidColumnIndexException in JDBC for more details on this JDBC
interview question.
What is difference between RowSet and
ResultSet in JDBC?
One
of the popular JDBC interview question now days. RowSet extends ResultSet and add support for JDBC API to Java
bean component model. Main difference of ResultSet and RowSet is RowSet being connected and disconnected,
which is another follow-up JDBC question. RowSet makes it easy to use ResultSet but as I said you only like to use it
to get benefit of disconnected and connected RowSet.
What
is use of setAutoCommit(false) in JDBC ?
This is one of the JDBC Interview question I
touched on Top
10 JDBC best practices for Java programmer.
makingsetAutoCommit(false) saves
a lot of performance as it doesn't commit transaction automatically after each
query and we do batch update. It allows you to handle it using commit() and rollback(). This has result in impressive
performance gain in DAO layer.
How to call stored procedure from JDBC in
Java?
This JDBC Interview question is another one
you can add on any frequently asked list and just can't afford not to prepare.
Mostly asked to Java
developers with 2 to 4 years experience. In its simplicity you
can just say that CallableStatement is used to call stored procedure,
which may lead questions like how
do you pass parameters to stored procedure from Java or difference
between IN and OUT parameters in JDBC etc.
It's worth to prepare this JDBC question in detail. By the way IN parameter is
used to pass input to stored procedure and OUT parameter is used to store
output return from stored procedure. IF your stored procedure return multiple
values than you can also use ResultSet to traverse all results.
What
is difference between Connected and disconnected RowSet in JDBC?
I
have seen this JDBC question asked as a follow-up question of previous JDBC
interview question RowSet vsResultSet. Main difference between connected and
disconnected RowSet in JDBC is that disconnected RowSet doesn't require JDBC Connection while
it's on disconnected state. This makes disconnected RowSet light and ideal to use in thin
clients, while connected RowSet is just a wrapper around ResultSet. JDBCRowSet and WebRowSet are two examples of connected RowSet
while a CachedRowSet is an example of disconnected RowSet
which caches data in memory. Ideal for small data set and thin Java clients with
small memory foot print.
What is difference between Statement,
PreparedStatement and CallableStatement in Java?
One
of the classical JDBC interview question. Main difference between Statement and PreparedSatement is performance and avoiding SQL Injection
as we have seen in Benefits
of using PreparedStatement in Java. While CallableStatement
has very specific use in JDBC and used to call stored procedure from Java
program
That's
all on these 11 JDBC Interview questions and answers article. As I said many
times, JDBC questions are important part of any Java interview, let it core
Java or J2EE Interview and you just can't ignore it. Always prepare JDBC well
enough to answer any JDBC Interview question to perform well in Java interviews
What
are the select and non-select operations in jdbc?
à
execute () and execute Update() are non select
àExecuteQuery
() select operation
What
is the diff b/w DriverManager class and DataSource interface?
The main diff b/w DriverManager class and dataSource
interface is DariverManager class doesn’t support connection pooling but
DataSource interface supports connection pooling.
àDriverManager
class doesn’t provide reusable connections .but DataSource interface provides
reusable connections
What
is CallableStatement?
It is an interface. It is used to call procedure
from database or to call the functions
In procedures we have three parameters
.in
parameter
.out
parameter
.inout
parameter
Explain the different types of Transaction Isolation Levels.
What is a "dirty read"?
What is the fastest type of JDBC driver?
What is the difference between different JDBC drivers?
What are collection pools? What are the advantages?
What is cold backup, hot backup, warm backup recovery?
What is the difference between cached rowset, jdbrowset and webrowset?
What is Metadata and why should I use it?
What is the difference between Statement, PreparedStatement and CallableStatemen?
What are different types of isolation levels in JDBC and explain where you can use them?
What actually does Class.forName("mypackage.MyDriver"); method do?
How do you get Column names only for a table (SQL Server)? Write the Query.
What is a data source?
What is 2 phase commit?
How do you handle your own transaction ?
What Class.forName will do while loading drivers?
Can we maintain two database connection in single application? How can we achieve that?
What is the normal procedure followed by a java client to access the db?
Explain the advantage of using PreparedStatement.
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
How to call a Stored Procedure from JDBC?
How does the Application server handle the JMS Connection?
When we will Denormalize data?
What is the query used to display all tables names in SQL Server (Query analyzer)?
Is the JDBC-ODBC Bridge multi-threaded?
How to Retrieve Warnings?
what are stored procedures? How is it useful?
How many types of JDBC Drivers are present and what are they?