JDBC
JDBC
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is currently
known as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard Edition). The
Java EE provides a platform for developers with enterprise features such as distributed
computing and web services. Java EE applications are usually run on reference run times such as
microservers or application servers. Examples of some contexts where Java EE is used are e-
commerce, accounting, banking information systems.
Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing from
database in a transactional way, managing distributed queues. The Java EE contains several APIs
which have the functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors,
Servlets, Java Server Pages and several web service technologies.
Java SE vs Java EE
Java SE refers to standard edition and contains basic functionalities and packages required by a
beginner or intermediate-level programmer. Java EE is an enhanced platform and a wrapper
around Java SE. It has the edge over Java SE an also has a variety of aspects in which it outshines
other features.
Java SE Java EE
Java SE provide basic functionalities such as Java EE facilitates development of large scale
defining types and objects. applications.
It has features like class libraries, deployment Java EE is a structured application with a
environments, etc. separate client, business, and Enterprise
layers.
It is mostly used to develop APIs for Desktop It is mainly used for developing web
Applications like antivirus software, game, applications.
etc.
Suitable for beginning Java developers. Suitable for experienced Java developers who
build enterprise-wide applications.
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to
connect with the database. There are four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC
API, we can save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for
JDBC API. A list of popular interfaces of JDBC API are given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
A list of popular classes of JDBC API are given below:
• DriverManager class
• Blob class
• Clob class
• Types class
Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent
and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
6. JDBC-ODBC bridge driver
7. Native-API driver (partially java driver)
8. Network Protocol driver (fully java driver)
9. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses 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 thin driver.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC function
calls.
• The ODBC driver needs to be installed on the client machine.
2) Native-API 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.
Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depend on the Database.
Class.forName("oracle.jdbc.driver.OracleDriver");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
1) public static synchronized void is used to register the given driver with
registerDriver(Driver driver): DriverManager. No action is performed by the
method when the given driver is already
registered.
2) public static synchronized void is used to deregister the given driver (drop the
deregisterDriver(Driver driver): driver from the list) with DriverManager. If
the given driver has been removed from the
list, then no action is performed by the
method.
7) pubic static void setLoginTimeout(int sec) The method provides the time in seconds. sec
mentioned in the parameter is the maximum
time that a driver is allowed to wait in order
to establish a connection with the database. If
0 is passed in the parameter of this method,
the driver will have to wait infinitely while
trying to establish the connection with the
database.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish a
connection with the database.
The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData,
i.e., an object of Connection can be used to get the object of Statement and DatabaseMetaData.
The Connection interface provide many methods for transaction management like commit(),
rollback(), setAutoCommit(), setTransactionIsolation(), etc.
By default, connection commits the changes after executing queries.
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to execute
SQL queries.
TRANSACTION_READ_COMMITTED: It is a constant which shows that the dirty reads are not
allowed. However, phantom reads and non-repeatable reads can occur.
TRANSACTION_READ_UNCOMMITTED: It is a constant which shows that dirty reads, non-
repeatable reads, and phantom reads can occur.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface
Let’s see the simple example of Statement interface to insert, update and delete the record.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as
well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next
from the current position.
2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
3) public boolean first(): is used to move the cursor to the first row in
result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified
row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be
positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column
index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified column
name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column
index of the current row as String.
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE)
;
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter
index.
public void setString(int paramIndex, String sets the String value to the given parameter
value) index.
public void setFloat(int paramIndex, float sets the float value to the given parameter
value) index.
public void setDouble(int paramIndex, double sets the double value to the given parameter
value) index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
import java.sql.*;
class InsertPrepared{
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");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
Answer: a
Explanation:
Answer: d
Explanation: JDBC API is divided into two packages i.e. java.sql and javax.sql. We have to import
these packages to use classes and interfaces in our application.
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
i. Type 3 Driver
j. Type-2 Driver
k. Type-4 Driver
l. Type-1 Driver
Hide Answer Workspace
Answer: c
Explanation: The JDBC thin driver is a pure Java driver. It is also known as Type-4 Driver. It is
platform-independent so it does not require any additional Oracle software on the client-side. It
communicates with the server using SQL *Net to access Oracle Database.
Answer: b
Explanation: To create a database connection in Java, we must follow the sequence given below:
q. executeResult()
r. executeQuery()
s. executeUpdate()
t. execute()
Hide Answer Workspace
Answer: c
Explanation: We use the executeUpdate() method for DML SQL queries that change data in the
database, such as INSERT, UPDATE, and DELETE which do not return a resultset.
6) How many transaction isolation levels provide the JDBC through the Connection interface?
u. 3
v. 4
w. 7
x. 2
Hide Answer Workspace
Answer: b
Explanation: The following table defines transaction isolation levels.
y. getConnection()
z. prepareCall()
aa. executeUpdate()
bb. executeQuery()
Hide Answer Workspace
Answer: A
Explanation: A Java application using the JDBC API establishes a connection to a database by
obtaining a Connection object. The standard way to obtain a Connection object is to call the
method DriverManager.getConnection() method that accepts a String contains the database
connection URL. It is a static and synchronized method.
cc. getConnection()
dd. registerDriver()
ee. forName()
ff. Both b and c
Hide Answer Workspace
Answer: d
Explanation: There are two ways to load a database driver in JDBC:
• By using the registerDriver() Method: To access the database through a Java application,
we must register the installed driver in our program. We can do this with the
registerDriver() method that belongs to the DriverManager class. The registerDriver()
method takes as input a driver class, that is, a class that implements the java.sql.Driver
interface, as is the case with OracleDriver.
• By using the Class.forName() Method: Alternatively, we can also use the forName()
method of the java.lang.Class to load the JDBC drivers directly. However, this method is
valid only for JDK-compliant Java virtual machines. It is invalid for Microsoft JVMs.
gg. ParameterizedStatement
hh. PreparedStatement
ii. CallableStatement and Parameterized Statement
jj. All kinds of Statements
Hide Answer Workspace
Answer: b
Explanation: The PreparedStatement interface extends the Statement interface. It represents a
precompiled SQL statement that can be executed multiple times. It accepts parameterized SQL
quires. We can pass 0 or more parameters to this query.
kk. Statement
ll. PreparedStatement
mm. QueryStatement
nn. CallableStatement
Hide Answer Workspace
Answer: c
Explanation:
• Statement: Use this for general-purpose access to your database. It is useful when we are
using static SQL statements at runtime. The Statement interface cannot accept
parameters.
• PreparedStatement: It represents the pre-compiled SQL statements that can be executed
multiple times.
• CallableStatement: It is used to execute SQL stored procedures.
• QueryStatement: It is not supported by JDBC.
11) Identify the isolation level that prevents the dirty in the JDBC Connection class?
oo. TRANSACTION_READABLE_READ
pp. TRANSACTION_READ_COMMITTED
qq. TRANSACTION_READ_UNCOMMITTED
rr. TRANSACTION_NONE
Hide Answer Workspace
Answer: b
Explanation: The isolation level TRANSACTION_READ_COMMITTED prevents the dirty read but
non-repeatable reads and phantom reads can occur.
12) What does setAutoCommit(false) do?
Answer: b
Explanation: The way to allow two or more statements to be grouped into a transaction is to
disable the auto-commit mode. After the auto-commit mode is disabled, no SQL statements are
committed until we call the commit() method explicitly.
ww. CallableStatement
xx. Statement
yy. CalledStatement
zz. PreparedStatement
Hide Answer Workspace
Answer: b
Explanation: The stored procedure is a database program that can be utilized to perform CRUD
tasks with the table. We can call these procedures by using the Statement Interface. It provides
methods to execute queries with the database.
14) What should be the correct order to close the database resource?What should be the correct order
to close the database resource?
Answer: d
Explanation: The golden rule to JDBC connections and statements is to close in the reverse order
of initiation or opening. In addition, the ResultSet is dependant on the execution of the Statement
and the Statement is dependant on the Connection instance. Hence, the closing should occur in
that order (ResultSet, Statement, and then Connection).
Answer: a
Explanation: The JDBC Driver supports both DriverManager and DataSource tracing as
documented in the JDBC 3.0 API specification. Trace information consists of JDBC API method
entry and exit points with the corresponding parameter and returns values.
DriverManager.setLogWriter method to send trace messages to a PrintWriter. The trace output
contains a detailed listing of the JDBC activity.
16) Which JDBC driver can be used in servlet and applet both?
iii. Type 3
jjj. Type 4
kkk. Type 3 and Type 2
lll. Type 3 and Type 4
Hide Answer Workspace
Answer: d
Explanation: Type 3 driver follows the three-tier approach which is used to access the databases.
The JDBC clients use standard network sockets to communicate with a middleware application
server. In a Type 4 driver, a pure Java-based driver that communicates directly with the vendor's
database through a socket connection.
Answer: c
Explanation: Type 1 driver is also known as the JDBC-ODBC bridge driver. It is a database driver
implementation that employs the ODBC driver to connect to the database. The driver converts
JDBC method calls into ODBC function calls.
Answer: d
Explanation: JDBC Net pure Java driver (Type 4) is the fastest driver because it converts the JDBC
calls into vendor-specific protocol calls and it directly interacts with the database.
uuu. TYPE_FORWARD_ONLY
vvv. CONCUR_WRITE_ONLY
www. TYPE_SCROLL_INSENSITIVE
xxx. TYPE_SCROLL_SENSITIVE
Hide Answer Workspace
Answer: b
Explanation: There are three types of ResultSet object:
• TYPE_FORWARD_ONLY: This is the default type and the cursor can only move forward in
the result set.
• TYPE_SCROLL_INSENSITIVE: The cursor can move forward and backward, and the result
set is not sensitive to changes made by others to the database after the result set was
created.
• TYPE_SCROLL_SENSITIVE: The cursor can move forward and backward, and the result set
is sensitive to changes made by others to the database after the result set was created.
Based on the concurrency there are two types of ResultSet object.
Answer: a
Explanation: JDBC Savepoint helps us in creating checkpoints in a transaction and we can rollback
to that particular checkpoint.
21) How many stages are used by Java programmers while using JDBC in their programs?
cccc. 3
dddd. 2
eeee. 5
ffff.6
Hide Answer Workspace
Answer: d
Explanation: There are following stages in a JDBC program:
Answer: a
Explanation: By creating an object to the driver class of the driver software, we can register the
driver. To register the JdbcOdbcDriver of the sun microsystems, we can create an object to the
driver class JdbcOdbcDriver, as follows:
sun.jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();
kkkk. 2
llll. 3
mmmm. 4
nnnn. 5
Hide Answer Workspace
Answer: c
Answer: d
Explanation: Data Source Name (DSN) is a name given to the database to identify it in the Java
program. The DSN is linked with the actual location of the database.
25) Which statement is correct if we want to connect the Oracle database using the thin driver provided
by Oracle Corp.?
Answer: a
Explanation: We use the following statement to connect Oracle database using the thin driver.
DriverManager.getConnection("jdbc::thin@localhost:1521:oracle",
"scott", "tiger");
Answer: d
Explanation: JDBC provides only two types of ResultSets: Forward and Scrollable ResultSet.
Answer: c
Explanation: SQL offers BLOB (Binary Large OBject) data type to store image files like .gif or .jpg
or jpeg into the database table.
28) Which data type is used to store files in the database table?
eeeee. BLOB
fffff. CLOB
ggggg. File
hhhhh. Both a and b
Hide Answer Workspace
Answer: b
Explanation: To store a large volume of data such as text file into a table, we use CLOB (Character
Large OBject) data type of SQL.
Answer: a
Explanation: DatabaseMetaData is an interface that is used to get Comprehensive information
about the database as a whole. It is implemented by driver vendors to let users know the
capabilities of a DBMS in combination with the JDBC driver that is used with it.
30) Which of the following driver converts the JDBC calls into database-specific calls?
Answer: b
Explanation: Type 2 driver converts JDBC calls into database-specific calls with the help of vendor
database library. It directly communicates with the database server.
Answer: b
Explanation: By default, a ResultSet object is not updatable and its cursor moves only in the
forward direction. If we want to create an updateable ResultSet object, either we can use
ResultSet.TYPE_SCROLL_INSENSITIVE or the ResultSet.TYPE_SCROLL_SENSITIVE type, which
moves the cursor forward and backward relative to the current position.
32) Which of the following interface provides the commit() and rollback() methods?
Answer: c
Explanation: The connection interface provides the commit() and rollback() method. The
commit() method makes all changes made since the previous commit/rollback permanent and
releases any database locks currently held by this Connection object. The rollback() method
undoes all changes made in the current transaction and releases any database locks currently
held by this Connection object.
yyyyy. 2
zzzzz. 1
aaaaaa. 3
bbbbbb. Multiple
Hide Answer Workspace
Answer: d
Explanation: Multiple statements can be created and used on the same connection, but only one
resultset at once can be created and used on the same statement.
34) JDBC API supports____________ and __________ architecture model for accessing the database.
cccccc. Two-tier
dddddd. Three-tier
eeeeee. Both a and b
ffffff. Only b
Hide Answer Workspace
Answer: c
Explanation: The JDBC API supports both two-tier and three-tier processing models for database
access. In the two-tier model, a Java application talks directly to the data source. In the three-tier
model, commands are sent to a "middle tier" of services, which then sends the commands to the
data source.
i. A transaction is a set of one or more SQL statements that make up a logical unit of work.
ii. A transaction ends with either a commit or a rollback, depending on whether there are any
problems with data consistency or data concurrency.
iii. A lock is a mechanism that allows two transactions from manipulating the same data at the
same time.
iv. To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by
others to the data that is being accessed by the transaction.