0% found this document useful (0 votes)
452 views

JDBC Interview Questions

Java

Uploaded by

PavanKumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
452 views

JDBC Interview Questions

Java

Uploaded by

PavanKumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

JDBC INTERVIEW QUESTIONS

http://www.tuto rialspo int.co m/jdbc/jdbc_inte rvie w_que stio ns.htm

Co pyrig ht tuto rials po int.co m

Dear readers, these J DBC Interview Q uestions have been desig ned specially to g et you acquainted with
the nature of questions you may encounter during your interview for the subject of J DBC. As per my
experience g ood interviewers hardly plan to ask any particular question during your interview, normally
questions start with some basic concept of the subject and later they continue based on further discussion and
what you answer:
Q : What is J DBC?
A: JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java prog ramming lang uag e and a wide rang e of databases.
Q : Desc ribe a g eneral J DBC Arc hitec ture.
A: General JDBC Architecture consists of two layers: J DBC API (T his provides the application-to-JDBC
Manag er connection) and J DBC Driver API (T his supports the JDBC Manag er-to-Driver Connection).
Q : What are the c ommon J DBC API c omponents?
A: JDBC API consists of following interfaces and classes: DriverManag er, Driver, Connection, Statement,
ResultSet, SQLException.
Q : What is a J DBC DriverManag er?
A: JDBC DriverManag er is a class that manag es a list of database drivers. It matches connection requests from
the java application with the proper database driver using communication subprotocol.
Q : What is a J DBC Driver?
A: JDBC driver is an interface enabling a Java application to interact with a database. T o connect with individual
databases, JDBC requires drivers for each database. T he JDBC driver g ives out the connection to the database
and implements the protocol for transferring the query and result between client and database
Q : What is a c onnec tion?
A: Connection interface consists of methods for contacting a database. T he connection object represents
communication context.
Q : What is a statement?
A: Statement encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned
and executed.
Q : What is a ResultSet?
A: T hese objects hold data retrieved from a database after you execute an SQL query using Statement objects.
It acts as an iterator to allow you to move throug h its data. T he java.sql.ResultSet interface represents the result
set of a database query.
Q : What are types of ResultSet?
A: T here are three constants which when defined in result set can move cursor in resultset backward, forward
and also in a particular row.
1. ResultSet.T YPE_FORWARD_ONLY: T he cursor can only move forward in the result set.
2. ResultSet.T YPE_SCROLL_INSENSIT IVE: T he cursor can scroll forwards and backwards, and the
result set is not sensitive to chang es made by others to the database that occur after the result set was
created.
3. ResultSet.T YPE_SCROLL_SENSIT IVE: T he cursor can scroll forwards and backwards, and the result
set is sensitive to chang es made by others to the database that occur after the result set was created.

Q : What are the basic steps to c reate a J DBC applic ation?


A: Following are the basic steps to create a JDBC application:
1. Import packag es containing the JDBC classes needed for database prog ramming .
2. Reg ister the JDBC driver, so that you can open a communications channel with the database.
3. Open a connection using the DriverManag er.g etConnection () method.
4. Execute a query using an object of type Statement.
5. Extract data from result set using the appropriate ResultSet.g etXXX () method.
6. Clean up the environment by closing all database resources relying on the JVM's g arbag e collection.
Q : What are J DBC driver types?
A: T here are four types of JDBC drivers:
1. JDBC-ODBC Bridg e plus ODBC driver, also called T ype 1: calls native code of the locally available
ODBC driver.
2. Native-API, partly Java driver, also called T ype 2: calls database vendor native library on a client side.
T his code then talks to database over network.
3. JDBC-Net, pure Java driver, also called T ype 3 : the pure-java driver that talks with the server-side
middleware that then talks to database.
4. Native-protocol, pure Java driver, also called T ype 4: the pure-java driver that uses database native
protocol.
Q : When should eac h of the J DBC driver type be used?
A: Following is a list as to when the four types of drivers can be used:
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred
driver.
T ype 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your
database.
T he type 1 driver is not considered a deployment-level driver and is typically used for development and
testing purposes only.
Q : Whic h type of J DBC driver is the fastest one?
A: JDBC Net pure Java driver(T ype 4) is the fastest driver because it converts the JDBC calls into vendor
specific protocol calls and it directly interacts with the database.
Q : Does the J DBC-O DBC Bridg e support multiple c onc urrent open statements per
c onnec tion?
A: No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridg e.
Q : What are the standard isolation levels defined by J DBC?
A: T he standard isolation levels are:
T RANSACT ION_NONE
T RANSACT ION_READ_COMMIT T ED
T RANSACT ION_READ_UNCOMMIT T ED

T RANSACT ION_REPEAT ABLE_READ


T RANSACT ION_SERIALIZ ABLE
Q : What is the desig n pattern followed by J DBC?
A: JDBC architecture decouples an abstraction from its implementation. Hence JDBC follows a bridg e desig n
pattern. T he JDBC API provides the abstraction and the JDBC drivers provide the implementation. New drivers
can be plug g ed-in to the JDBC API without chang ing the client code.
Q : What are the different types of J DBC Statements?
A: T ypes of statements are:
Statement (reg ular SQL statement)
PreparedStatement (more efficient than statement due to pre-compilation of SQL)
CallableStatement (to call stored procedures on the database)
Q : What is differenc e between statement and prepared statement?
A: Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the
same execution plan for different arg uments rather than creating a new execution plan every time. Prepared
statements use bind arg uments, which are sent to the database eng ine. T his allows mapping different requests
with same prepared statement but different arg uments to execute the same execution plan. Prepared statements
are more secure because they use bind variables, which can prevent SQL injection attack.
Q : How do you reg ister a driver?
A: T here are 2 approaches for reg istering the Driver:
Class.forName(): T his method dynamically loads the driver's class file into memory, which automatically
reg isters it. T his method is preferable because it allows you to make the driver reg istration config urable
and portable.
DriverManag er.reg isterDriver(): T his static method is used in case you are using a non-JDK compliant
JVM, such as the one provided by Microsoft.
Q : What are the benefits of J DBC 4.0?
A: Here are few advantag es of JDBC 4.0
1. Auto loading of JDBC driver class. In the earlier versions we had to manually reg ister and load drivers
using class.forName.
2. Connection manag ement enhancements. New methods added to javax.sql.PooledConnection.
3. DataSet Implementation of SQL using annotations.
4. SQL XML support.
Q : What do you mean by fastest type of J DBC driver?
A: JDBC driver performance or fastness depends on a number of issues: Quality of the driver code, size of the
driver code, database server and its load, Network topolog y, Number of times your request is translated to a
different API.
Q : In real time projec t whic h driver did you use?
A: T ell about your real time experience.
Q : How do you c reate a c onnec tion objec t?
A: T here are 3 overloaded DriverManag er.g etConnection() methods to create a connection object:
1. g etConnec tion(String url, String user, String password):Using a database URL with a

username and password. For example:


String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);

2. g etConnec tion(String url):Using only a database URL. For example:


String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);

3. g etConnec tion(String url, Properties prop):Using a database URL and a Properties object.
For example:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );

Q : How c an I determine whether a Statement and its ResultSet will be c losed on a c ommit or
rollbac k?
A: Use the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() and
supportsOpenStatementsAcrossRollback() to check.
Q : Is there a prac tic al limit for the number of SQ L statements that c an be added to an
instanc e of a Statement objec t
A: T he specification makes no mention of any size limitation for Statement.addBatch(), this is dependent, on the
driver.
Q : How c ursor works in sc rollable result set?
A: T here are several methods in the ResultSet interface that involve moving the cursor, like: beforeFirst(),
afterLast(), first(), last(), absolute(int row), relative(int row), previous(), next(), g etRow(), moveT oInsertRow(),
moveT oCurrentRow().
Q : How c an you view a result set?
A: ResultSet interface contains g et methods for each of the possible data types, and each g et method has two
versions:
1. One that takes in a column name.
2. One that takes in a column index.
For e.g .: g etInt(String columnName), g etInt(int columnIndex)
Q : How do you update a result set?
A: ResultSet interface contains a collection of update methods for updating the data of a result set. Each update
method has two versions for each data type:
1. One that takes in a column name.
2. One that takes in a column index.
T hese methods chang e the columns of the current row in the ResultSet object, but not in the underlying
database. T o update your chang es to the row in the database, you need to invoke one of the following methods:
updateRow(), deleteRow(), refreshRow(), cancelRowUpdates(), insertRow()
Q : How does J DBC handle the data types of J ava and database?

A: T he JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL
INT EGER.
Q : What c auses "No suitable driver" error?
A: "No suitable driver" is occurs during a call to the DriverManag er.g etConnection method, may be of any of the
following reason:
1. Due to failing to load the appropriate JDBC drivers before calling the g etConnection method.
2. It can be specifying an invalid JDBC URL, one that is not recog nized by JDBC driver.
3. T his error can occur if one or more the shared libraries needed by the bridg e cannot be loaded.
Q : How do you handle SQ L NULL values in J ava?
A: SQL's use of NULL values and Java's use of null are different concepts. T here are three tactics you can use:
1. Avoid using g etXXX( ) methods that return primitive data types.
2. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test
whether the wrapper class variable that received the value returned by the g etXXX( ) method should be
set to null.
3. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive
variable that received the value returned by the g etXXX( ) method should be set to an acceptable value
that you've chosen to represent a NULL.
Q : What does setAutoCommit do?
A: When a connection is created, it is in auto-commit mode. T his means that each individual SQL statement is
treated as a transaction and will be automatically committed rig ht after it is executed. By setting auto-commit to
false no SQL statements will be committed until you explicitly call the commit method.
Q : Why will you set auto c ommit mode to false?
A: Following are the reasons:
1. T o increase performance.
2. T o maintain the integ rity of business processes.
3. T o use distributed transactions
Q : What is SavePoint?Give an example.
A: A savepoint marks a point that the current transaction can roll back to. Instead of rolling all of its chang es back,
it can choose to roll back only some of them. For example, suppose you:
start a transaction
insert 10 rows into a table
set a savepoint
insert another 5 rows
rollback to the savepoint
commit the transaction
After doing this, the table will contain the first 10 rows you inserted. T he other 5 rows will have been deleted by
the rollback. A savepoint is just a marker that the current transaction can roll back to.
Q : What are SQ L warning s?

A: SQLWarning objects are a subclass of SQLException that deal with database access warning s. Warning s do
not stop the execution of an application, as exceptions do. T hey simply alert the user that something did not
happen as planned. A warning can be reported on a Connection object, a Statement object (including
PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a
g etWarning s method.
Q : Why would you use a batc h proc ess?
A: Batch Processing allows you to g roup related SQL statements into a batch and submit them with one call to the
database.
Q : What are the steps followed to c reate a batc h proc ess?
A: T ypical sequences of steps to use Batch Processing with Statement or PrepareStatement Object are:
1. In case of Batch processing using PrepareStatement object, create SQL statements with placeholders.
2. Create a Statement or PrepareStatement object using either createStatement() or prepareStatement()
methods respectively.
3. Set auto-commit to false using setAutoCommit().
4. Add as many as SQL statements you like into batch using addBatch() method on created statement object.
5. Execute all the SQL statements using executeBatch() method on created statement object.
6. Finally, commit all the chang es using commit() method.
Q : What is a Stored Proc edure and how do you c all it in J DBC?
A: A stored procedure is a g roup of SQL statements that form a log ical unit and perform a particular task. For
example operations on an employee database (hire, fire, promote, lookup) could be coded as stored
procedures executed by application code. Stored procedures can be called using CallableStatement class in
JDBC API. For example the following code demonstrates this:
CallableStatement cs = con.prepareCall("{call MY_SAMPLE_STORED_PROC}");
ResultSet rs = cs.executeQuery();

Q : What is J DBC SQ L esc ape syntax?


A: T he escape syntax g ives you the flexibility to use database specific features unavailable to you by using
standard JDBC methods and properties.
T he g eneral SQL escape syntax format is as follows:
{keyword 'parameters'}.

JDBC defines escape sequences that contain the standard syntax for the following lang uag e features:
1. Date, time, and timestamp literals (d, t, ts Keywords).
2. Scalar functions such as numeric, string , and data type conversion functions(fn Keyword).
3. Outer joins(oj Keyword)
4. Escape characters for wildcards used in LIKE clauses(escape Keyword).
5. Procedure calls(call Keyword).
Q : What is a transac tion?
A: A transaction is a log ical unit of work. T o complete a log ical unit of work, several actions may need to be taken
ag ainst a database. T ransactions are used to provide data integ rity, correct application semantics, and a
consistent view of data during concurrent access.
Q : How will you insert multiple rows into a database in a sing le transac tion?

A: Follow steps as below:


//turn off the implicit commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();

a new transaction is implicitly started.


Q : When will you g et the messag e "No Suitable Driver"?
A: When a Connection request is issued, the DriverManag er asks each loaded driver if it understands the URL
sent. When the URL passed is not properly constructed, then the "No Suitable Driver" messag e is returned.
Q : What is the differenc e between exec ute, exec uteQ uery, exec uteUpdate?
A: boolean exec ute(): Executes the any kind of SQL statement
ResultSet exec uteQ uery(): T his is used g enerally for reading the content of the database. T he output will
be in the form of ResultSet. Generally SELECT statement is used.
int exec uteUpdate(): T his is g enerally used for altering the databases. Generally DROP T ABLE or
DAT ABASE, INSERT into T ABLE, UPDAT E T ABLE, DELET E from T ABLE statements will be used in this.
T he output will be in the form of int which denotes the number of rows affected by the query.
Q : Why do you have to c lose database c onnec tions in J ava?
A: You need to close the resultset, the statement and the connection. If the connection has come from a pool,
closing it actually sends it back to the pool for reuse. We can do this in the finally{} block, such that if an exception
is thrown, you still g et the chance to close this.
Q : What is the use of blob, c lob datatypes in J DBC?
A: T hese are used to store larg e amount of data into database like imag es, movie etc which are extremely larg e
in size.
Q : Resultset is an interfac e, how does it support rs.Next()?
A: Every vendor of Database provides implementation of ResultSet & other interfaces, throug h the Driver.
Q : What is Connec tion Pooling ?
A: Connection Pooling is a technique used for reuse of physical connections and reduced overhead for your
application. Connection pooling functionality minimizes expensive operations in the creation and closing of
sessions.Database vendor's help multiple clients to share a cached set of connection objects that provides
access to a database. Clients need not create a new connection everytime to interact with the database.
Q : How do you implement c onnec tion pooling
A: If you use an application server like WebLog ic, WebSphere, jBoss, T omcat. , then your application server
provides the facilities to config ure for connection pooling . If you are not using an application server then
components like Apache Commons DBCP Component can be used.
Q : O ut of byte[] or a java.sql.Blob, whic h has best performanc e when used to manipulate
data from database?
A: java.sql.Blob has better performance as it does not extract any data from the database until you explicitly ask it
to.
Q : O ut of String or a java.sql.Clob, whic h has best performanc e when used to manipulate
data from database?
A: java.sql.Clob has better performance as it does not extract any data from the database until you explicitly ask
it to.

Q : Suppose the SELECT returns 1000 rows, then how to retrieve the first 100 rows, then
g o bac k and retrieve the next 100 rows?
A: Use the Statement.setFetchSize method to indicate the size of each database fetch.
Q : What does the Class.forName("MyClass") do?
A: Class.forName("MyClass"):
1. Loads the class MyClass.
2. Execute any static block code of MyClass.
3. Returns an instance of MyClass.
Q : When you say Class.forName() loads the driver c lass, does it mean it imports the driver
c lass using import statement?
A: No, it doesn't. An import statement tells the compiler which class to look for. Class.forName() instructs the
Class class to find a class-loader and load that particular Class object into the memory used by the JVM.
Q : What we set the attribute Conc urrenc y in ResultSet?
A: T he ResultSet concurrency determines whether the ResultSet can be updated, or only read. A ResultSet can
have one of two concurrency levels:
1. ResultSet.CONCUR_READ_ONLY :means that the ResultSet can only be read.
2. ResultSet.CONCUR_UPDAT ABLE : means that the ResultSet can be both read and updated.
Q : What are the differenc es between setMaxRows(int) and SetFetc hSize(int)?
A: T he difference between setFetchSize(int) and setMaxRow(int) are:
setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs
more rows. setFetchSize(int) affects how the database returns the ResultSet data.
setMaxRows(int) method of the ResultSet specifies how many rows a ResultSet can contain at a time.
setMaxRows(int) affects the client side JDBC object.

Q : What is a RowSet?
A: A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a result
set. A RowSet objects are JavaBeans components.
Q : What are different types of RowSet objec ts?
A: T here are two types of RowSet:
1. Connec ted: A connected RowSet Object is permanent in nature. It doesn't terminate until the application
is terminated.
2. Disc onnec ted: A disconnected RowSet object is ad-hoc in nature. Whenever it requires retrieving data
from the database, it establishes the connection and closes it upon finishing the required task. T he data that
is modified during disconnected state is updated after the connection is re-established.
Q : What is a "dirty read"?
A: In typical database transactions, say one transaction reads and chang es the value while the second transaction
reads the value before committing or rolling back by the first transaction. T his reading process is called as 'dirty
read'. Because there is always a chance that the first transaction mig ht rollback the chang e which causes the
second transaction reads an invalid value.
Q : Whic h isolation level prevents dirty read in J DBC, c onnec tion c lass.

A: T RANSACT ION_READ_COMMIT T ED prevents dirty reads.


Q : What is Metadata and why should you use it?
A: JDBC API has two Metadata interfaces : DatabaseMetaData & ResultSetMetaData. T he meta data
provides comprehensive information about the database as a whole. T he implementation for these interfaces is
implemented by database driver vendors to let users know the capabilities of a Database.
Q : How to Connec t to an Exc el Spreadsheet using J DBC in J ava ?
A: Follow the steps below:
First setup the new ODBC datasource. Goto Administrative T ools->Data Sources (ODBC)->System DSN
tab->Add->Driver do Microsoft Excel(*.xls)->Finish. Now g ive the Data Source Name (SampleExcel) &
Description. Next, click Select Workbook and point to your excel sheet.
In the code make to following code additions:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:SampleExcel","","");
stmt=conn.createStatement();
sql="select * from [Sheet1$]";
rs=stmt.executeQuery(sql);

Where Sheet1 is the excel sheet name.


Q : What is differenc e between J DBC, J NDI and Hibernate?
A: Hibernate is an Object-Relational Mapping tool. It maps Objects to relational data.
T he J ava Naming and Direc tory Interfac e (J NDI) is an API to access different naming and directory
services. You use it to access something stored in a directory or naming service without haveing to code
specifically to that naming or directory service.
J ava DataBase Connec tivity (J DBC) API is an API to access different relational databases. You use it to
access relational databases without embedding a dependency on a specific database type in your code.

What is Next ?
Further you can g o throug h your past assig nments you have done with the subject and make sure you are able to
speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex
questions, rather you have to make your basics concepts very strong .
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you
answered, you must have answered with confidence. So just feel confident during your interview. We at
tutorialspoint wish you best luck to have a g ood interviewer and all the very best for your future endeavor.
Cheers :-)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy