Are you going to attend any interviews on JDBC? And feel that you are still not ready? Do not worry! Please go through this blog before attending the interview. This blog on JBDC Interview Questions will help you get acquainted with the nature of questions to be asked in a JDBC Interview which can boost your confidence.
Java Database Connectivity (JDBC) is an application programming interface (API) that the Java programming language uses, and it defines a procedure of clients' access to a database. It is a part of the Java Standard Edition platform offered by Oracle Corporation.
Here are some of the JDBC questions that give you clarity on the subject and take your confidence to the next level. The questions are sorted out according to the level of the candidates, i.e., the beginner's level and professional level.
We have divided this Interview questions blog into three sections for your easy understanding
Frequently Asked JBDC Interview Questions.
If you are new to this field, these are the fundamental questions mostly posed to freshers. Preparing these JDBC Interview Questions for Beginners first will help you face the interview confidently.
JDBC stands for Java Database Connectivity, a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.
A connection is an Interface that includes all methods for contacting a database. The connection object is a source of communication context, i.e., all communication with the database with the help of the connection object only.
Statement abstracts an SQL statement that must be parsed, planned, compiled, passed and executed.
ResultSet is the object that holds the data retrieved from a database after executing an SQL query with the use of Statement objects. ResultSet helps move through the data freely. The java.sql.ResultSet interface represents the result set of a database query.
Learn how to use JBOSS, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enrol on Free JBOSS Training Demo! |
JDBC driver is an interface that enables the interaction of Java applications with a database. Drivers are required for each database when JDBC connects with individual databases. The JDBC driver acts as a connection to the database, implementing the necessary protocols for transferring the query and result between client and database.
The class that handles a list of database drivers is called JDBC DriverManager. The connection requests are matched from the java application to the database driver using communication subprotocol.
A RowSet is an object that holds tabular data in an easily adaptable way to use rather than a result set. JavaBeans components are the RowSet objects.
The architecture of JDBC consists of two layers JDBC Driver API (The layer supports JDBC Manager-to-Driver Connection) and JDBC API (This layer provides the application-to-JDBC Manager connection).
The components and interfaces included in JDBC API are Driver, Connection, DriverManager, Statement, SQLException ResultSet.
JDBC Net pure Java driver(Type 4) is the fastest driver of all as it converts the JDBC calls into vendor-specific protocol calls and interacts directly with the database.
Statements used in JDBC are
Statement − which is a regular SQL statement.
PreparedStatement − is more efficient than a SQL Statement.
CallableStatement − is used to call stored procedures in the database.
The JDBC driver converts the Java data type to the appropriate JDBC type. It uses default mapping for most data types. For example, a Java int is converted to an SQL INTEGER.
The size of the driver code, Quality of the driver code, database server and its load, Network topology, Number of times the request is translated to a different API are all the number of issues that decide the speed of a JDBC driver.
To view the result set, we use the get methods. Each get method in the ResultSet interface provides two versions.
Ex: getInt(String columnName), getInt(int columnIndex)
AutoCommit ensures that every individual SQL statement is committed right after its execution when it is set in auto-commit mode. When created, any connection is in auto-commit mode by default. When the auto-commit is false, no SQL statements will be committed until explicitly called by the commit method.
Setting auto-commit mode to false
Batch Processing allows us to group related SQL statements into one single batch and then call the whole batch with one call to the database.
Check out: Installing the JDBC driver |
The logical unit of work is called a transaction. It needs several actions against a database to complete a logical unit of work. Transactions provide data integrity, correct application semantics, and a consistent view of data during concurrent access.
When a Connection request is issued, the DriverManager asks each loaded driver to understand the URL sent. When the URL is not properly constructed, the "No Suitable Driver" message is returned.
A database connection should be closed to help release other database resources like handles, cursor, etc. With every execution, the resultset, the connection and the statement. If the connection is made with a pool, closing it sends it back to the pool for reuse. This is done in the finally{} block so that if an exception is thrown, we can still close it.
The blob, clob datatypes are used to store large amounts of large-sized data into databases like movies, images, etc.
The next() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the next row, from the current position.
JDBC API has two Metadata interfaces DatabaseMetaData & ResultSetMetaData. The metadata provides data about the data that is stored in the database. These interfaces are implemented by database driver vendors to tell the capabilities of a Database to the users.
A savepoint is a point that sets up the mark/point to which the current transaction can be rolled back. This means one can choose which extent or the point the data should be rolled back to. For example, observe the procedure and use of savepoint.
The table will contain the first ten rows inserted at the start of these instructions. The rollback will have deleted the other five rows. A savepoint is just a marker to which the current transaction can rollback.
If you are an experienced candidate in this domain with experience of at least 2+ years, these are the most likely questions an interviewer. Preparing yourself with JDBC Interview questions will enhance your knowledge and confidence.
Three constants in the ResultSet can move the cursor backwards, forward, and in a particular row when defined in the result set.
Here are the steps to create a JDBC application
There are four types of JDBC drivers:
Following are the application instances of the four types of drivers
No. Only one Statement object can be made per connection using the JDBC-ODBC Bridge.
JDBC defines the following standard isolation levels:
JDBC follows a bridge design pattern. The JDBC API provides the abstraction, and the JDBC drivers provide the implementation. New drivers can be plugged-in to the JDBC API without changing the client code.
A Statement is used to access the database. A Statement interface cannot accept parameters, but it is useful when using static SQL statements at runtime. If SQL queries are to be run only once, this Statement interface is preferred over PreparedStatement.
Prepared statements are pre-compiled and offer better performance. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. Prepared statements are more secure as they use bind variables to prevent SQL injection attacks.
There are two ways described for registering the Driver
Benefits of JDBC 4.0:
There are three overloaded DriverManager.getConnection() methods to create a connection object
getConnection(String URL, String user, String password)Using a database URL with a username and password. For example
String URL = "jdbcoraclethin@amrood1521EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
getConnection(String Url)Using only a database URL. For example
String URL = "jdbcoraclethinusername/password@amrood1521EMP";
Connection conn = DriverManager.getConnection(URL);
getConnection(String URL, Properties prop)Using a database URL and a Properties object. For example
String URL = "jdbcoraclethin@amrood1521EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Check using the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() and supportsOpenStatementsAcrossRollback() to check if the Statement and its ResultSet will be closed on a commit or rollback.
There is no size limit for Statement.addBatch(). It is dependent on the driver.
Several methods decide how the cursor moves in the database like first(), last(), beforeFirst(), afterLast(), absolute(int row), relative(int row), previous(), next(), getRow(), moveToInsertRow(), moveToCurrentRow().
The methods in the ResultSet change the columns of the current row in the ResultSet object but not in the underlying database. To update the changes to the row in the database, invoking of one of the following methods is required
updateRow(), deleteRow(), refreshRow(), cancelRowUpdates(), insertRow()
"No suitable driver" occurs during a call to the DriverManager using the getConnection method. It may occur due to any of the following reasons.
SQL's use of NULL values is very different from Java's use of null values. These values can be handled in three ways.
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 getXXX( ) method should be set to null.
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do. They 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 getWarnings method.
Batch Processing with Statement or PrepareStatement Object can be done using the following steps:
A stored procedure is a group of SQL statements that form a logical unit to perform a particular task. For example, operations on an employee database (hire, fire, promote, lookup) can be coded as stored procedures which are then executed by application code. These Stored procedures are called using CallableStatement class in JDBC API. The code to explain this is given below:
CallableStatement cs = con.prepareCall("{call MY_SAMPLE_STORED_PROC}");
ResultSet rs = cs.executeQuery();
The escape syntax gives the flexibility to the user to use database-specific features which are not available when using standard JDBC methods and properties.
//turn off the implicit commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
//a new transaction is implicitly started.
Connection Pooling is a technique used for the reuse of physical connections. This reduces the overhead for the application. Connection pooling functionality minimises expensive operations in the creation and closing of sessions. Multiple clients can share a cached set of connection objects that provides access to a database with the help of database vendors.
When using application servers like JBoss, WebLogic, Tomcat, WebSphere, the application server provides the facilities to configure for connection pooling. Components like Apache Commons DBCP Component can be used when an application server is not involved.
java.sql.Blob has better performance as it does not involve data extraction from the database until it is asked explicitly.
It Loads the class MyClass.
Execute any static block code of MyClass.
Returns an instance of MyClass.
The value determines whether the ResultSet can be updated or only read. A ResultSet can have one of two concurrency levels
ResultSet.CONCUR_READ_ONLY − means that the ResultSet can only be read.
ResultSet.CONCUR_UPDATABLE − means that the ResultSet can be both read and updated.
The 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.
There are two types of RowSet
When one transaction reads and changes the value while the second transaction reads the value before committing or rolling back by the first transaction, this reading process is called a 'dirty read'. Because there is always a chance that the first transaction might roll back the change, which causes the second transaction to read an invalid value.
TRANSACTION_READ_COMMITTED prevents dirty reads.
Here in this blog, we have covered almost all of the topics related to JDBC to help you get yourself prepared. And these JDBC Interview Questions can come to your aid when attending an interview. Prepare well until you feel confident. All the best!
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
JBoss Training | Nov 19 to Dec 04 | View Details |
JBoss Training | Nov 23 to Dec 08 | View Details |
JBoss Training | Nov 26 to Dec 11 | View Details |
JBoss Training | Nov 30 to Dec 15 | View Details |
Usha Sri Mendi is a Senior Content writer with more than three years of experience in writing for Mindmajix on various IT platforms such as Tableau, Linux, and Cloud Computing. She spends her precious time on researching various technologies, and startups. Reach out to her via LinkedIn and Twitter.