0% found this document useful (0 votes)
49 views35 pages

JDBC

..

Uploaded by

Harsh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views35 pages

JDBC

..

Uploaded by

Harsh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Java EE

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.

1. Web Specifications of Java EE


• Servlet- This specification defines how you can manage HTTP requests either in a
synchronous or asynchronous way. It is low level, and other specifications depend on it
• WebSocket- WebSocket is a computer communication protocol, and this API provides a
set of APIs to facilitate WebSocket connections.
• Java Server Faces- It is a service which helps in building GUI out of components.
• Unified Expression Language- It is a simple language which was designed to facilitate web
application developers.
2. Web Service Specifications of Java EE
• Java API for RESTful Web Services- It helps in providing services having Representational
State Transfer schema.
• Java API for JSON Processing- It is a set of specifications to manage the information
provided in JSON format.
• Java API for JSON Binding- It is a set of specifications provide for binding or parsing a JSON
file into Java classes.
• Java Architecture for XML Binding- It allows binding of xml into Java objects.
• Java API for XML Web Services- SOAP is an xml based protocol to access web services over
http. This API allows you to create SOAP web services.
3. Enterprise Specifications of Java EE
• Contexts and Dependency Injection- It provides a container to inject dependencies as in
Swing.
• Enterprise JavaBean- It is a set of lightweight APIs that an object container possesses in
order to provide transactions, remote procedure calls, and concurrency control.
• Java Persistence API- These are the specifications of object-relational mapping between
relational database tables and Java classes.
• Java Transaction API- It contains the interfaces and annotations to establish interaction
between transaction support offered by Java EE. The APIs in this abstract from low-level
details and the interfaces are also considered low-level.
• Java Message Service- It provides a common way to Java program to create, send and
read enterprise messaging system's messages.
4. Other Specifications of Java EE
• Validation- This package contains various interfaces and annotations for declarative
validation support offered by Bean Validation API.
• Batch applications- It provides the means to run long running background tasks which
involve a large volume of data and which need to be periodically executed.
• Java EE Connector Architecture- This is a Java-based technological solution for connecting
Java servers to Enterprise Information System.
Setting up Java EE
Requirements
For the installation of latest SDK of Java EE which is Java EE 6 SDK on windows, you require to
have a minimum memory of 1GB, minimum Disk space of 250MB free and JVM Java SE 6. For
setting up Java EE, you require to have a JDK and then have an IDE preferably Eclipse as it is free.

Install a Java Development Kit


1. Browse to Oracle's Java SE Development Kit downloads
2. In the section titled Java SE Development Kit 9.0.1, read the license and, if you agree,
click Accept License Agreement
3. Still, in that section, click on JDK-9.0.1_windows-x64_bin.exe (or the right download for
your OS)
4. Run the downloaded JDK installer, using Run As Administrator
5. Add the Windows (or Linux) Environment Variable JAVA_HOME. Set it to the root folder
of your newly-installed JDK, which looks like C:\Program Files\Java\jdk1.8.0_51.
Install Eclipse for Java EE
1. Browse to Eclipse Downloads
2. Click on the Download button under Get Eclipse.

3. On the resulting page, click on the Download button.


Note: The version of Eclipse (32-bit or 64-bit) which you download should match the version of your JDK.
You installed JDK-9.0.1_windows-x64 above, so download the 64-bit Eclipse.
4. Run the downloaded installer using Run as Administrator.
5. Choose the version of Eclipse you wish to install. Eclipse IDE for Java EE developers is
preferable for Java work.
6. If the installation fails, try again with real-time virus scanning temporarily turned off.
Remember to turn it on again when it's done.

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.

SE is a normal Java specification EE is built upon Java SE. It provides


functionalities like web applications, and
Servlets.

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.

It does not provide user authentication. It provides user authentication.

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:

• JDBC-ODBC Bridge Driver,


• Native Driver,
• Network Protocol Driver, and
• Thin Driver

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:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
What is API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.

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.

In Java 8, the JDBC-ODBC Bridge has been removed.


Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

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.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
• No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

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.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
10. con.close();
DriverManager class
The DriverManager class is the component of JDBC API and also a member of the java.sql
package. The DriverManager class acts as an interface between users and drivers. It keeps track
of the drivers that are available and handles establishing a connection between a database and
the appropriate driver. It contains all the appropriate methods to register and deregister the
database driver class and to create a connection between a Java application and the database.
The DriverManager class maintains a list of Driver classes that have registered themselves by
calling the method DriverManager.registerDriver(). Note that before interacting with a Database,
it is a mandatory process to register the driver; otherwise, an exception is thrown.

Methods of the DriverManager Class


Method Description

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.

3) public static Connection is used to establish the connection with the


getConnection(String url) throws specified url. The SQLException is thrown
SQLException: when the corresponding Driver class of the
given database is not registered with the
DriverManager.

4) public static Connection is used to establish the connection with the


getConnection(String url,String specified url, username, and password. The
userName,String password) throws SQLException is thrown when the
SQLException: corresponding Driver class of the given
database is not registered with the
DriverManager.
5) public static Driver getDriver(String url) Those drivers that understand the mentioned
URL (present in the parameter of the method)
are returned by this method provided those
drivers are mentioned in the list of registered
drivers.

6) pubic static int getLoginTimeout() The duration of time a driver is allowed to


wait in order to establish a connection with
the database is returned by this 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.

8) public static Connection A connection object is returned by this


getConnection(String URL, Properties prop) method after creating a connection to the
throws SQLException database present at the mentioned URL,
which is the first parameter of this method.
The second parameter, which is "prop",
fetches the authentication details of the
database (username and password.). Similar
to the other variation of the getConnection()
method, this method also throws the
SQLException, when the corresponding Driver
class of the given database is not registered
with the DriverManager.

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.

2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a


Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status. By default, it is
true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.

Connection Interface Fields


There are some common Connection interface constant fields that are present in the Connect
interface. These fields specify the isolation level of a transaction.
TRANSACTION_NONE: No transaction is supported, and it is indicated by this constant.

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.

TRANSACTION_REPEATABLE_READ: It is a constant which shows that the non-repeatable reads


and dirty reads are not allowed. However, phantom reads and can occur.
TRANSACTION_SERIALIZABLE: It is a constant which shows that the non-repeatable reads, dirty
reads as well as the phantom reads are not allowed.

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();

//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where
id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}

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.

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.

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");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.

Let's see the example of parameterized query:

String sql="insert into emp values(?,?,?)";


As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?


Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}


Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:

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.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.

Example of PreparedStatement interface that inserts the record


First of all create table as given below:

create table emp(id number(10),name varchar2(50));


Now insert records in this table by the code given below:

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");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}

Multiple Choice Questions on JDBC in Java


JDBC is an API (Application Programming Interface) that helps a programmer to write a Java
program to connect to a database, retrieve the data from the database, and perform various
operations on the data in a Java program. As it is an important topic, the questions related to
JDBC frequently asked in Java interviews and competitive exams. So, in this section, we have
collected some multiple-choice questions based on JDBC that are important from the
perspective of different competitive exams and interviews.
1) What are the major components of the JDBC?

a. DriverManager, Driver, Connection, Statement, and ResultSet


b. DriverManager, Driver, Connection, and Statement
c. DriverManager, Statement, and ResultSet
d. DriverManager, Connection, Statement, and ResultSet
Hide Answer Workspace

Answer: a
Explanation:

• DriverManager: Manages a list of database drivers.


• Driver: The database communications link, handling all communication with the
database.
• Connection: Interface with all methods for contacting a database.
• Statement: Encapsulates an SQL statement which is passed to the database to be parsed,
compiled, planned, and executed.
• ResultSet: The ResultSet represents a set of rows retrieved due to query execution.

2) Select the packages in which JDBC classes are defined?

e. jdbc and javax.jdbc


f. rdb and javax.rdb
g. jdbc and java.jdbc.sql
h. sql and javax.sql
Hide Answer Workspace

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.

3) Thin driver is also known as?

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.

4) What is the correct sequence to create a database connection?


i. Import JDBC packages.
ii. Open a connection to the database.
iii. Load and register the JDBC driver.

iv. Execute the statement object and return a query resultset.


v. Create a statement object to perform a query.
vi. Close the resultset and statement objects.
vii. Process the resultset.

viii. Close the connection.

m. i, ii, iii, v, iv, vii, viii, vi


n. i, iii, ii, v, iv, vii, vi, viii
o. ii, i, iii, iv, viii, vii, v, vi
p. i, iii, ii, iv, v, vi, vii, viii
Hide Answer Workspace

Answer: b
Explanation: To create a database connection in Java, we must follow the sequence given below:

11. Import JDBC packages.


12. Load and register the JDBC driver.
13. Open a connection to the database.
14. Create a statement object to perform a query.
15. Execute the statement object and return a query resultset.
16. Process the resultset.
17. Close the resultset and statement objects.
18. Close the connection.

5) Which of the following method is used to perform DML statements in JDBC?

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.

Transaction Isolation Level Description

TRANSACTION_READ_UNCOMMITTED Dirty reads, non-repeatable reads, and


phantom reads can occur.

TRANSACTION_READ_COMMITTED Dirty reads are prevented; non-repeatable


reads and phantom reads can occur.

TRANSACTION_REPEATABLE_READ Dirty reads and non-repeatable reads are


prevented; phantom reads can occur.

TRANSACTION_SERIALIZABLE Dirty reads, non-repeatable reads, and


phantom reads are prevented.

7) Which of the following method is static and synchronized in JDBC API?

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.

8) Which methods are required to load a database driver in JDBC?

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.

9) Parameterized queries can be executed by?

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.

10) Which of the following is not a valid statement in JDBC?

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?

ss. It will not commit transactions automatically after each query.


tt. It explicitly commits the transaction.
uu. It never commits the transactions.
vv. It does not commit transaction automatically after each query.
Hide Answer Workspace

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.

13) Stored procedure can be called by using the ????..?

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?

aaa. Connection, Statements, and then ResultSet


bbb. ResultSet, Connection, and then Statements
ccc. Statements, ResultSet, and then Connection
ddd. ResultSet, Statements, and then Connection
Hide Answer Workspace

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).

15) A good way to debug JDBC-related problems is to enable???..?

eee. JDBC tracing


fff. Exception handling
ggg. Both a and b
hhh. Only b
Hide Answer Workspace

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.

17) JDBC-ODBC driver is also known as?


mmm. Type 4
nnn. Type 3
ooo. Type 1
ppp. Type 2
Hide Answer Workspace

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.

18) Which of the following driver is the fastest one?

qqq. JDBC-ODBC Bridge Driver


rrr. Native API Partly Java Driver
sss. Network Protocol Driver
ttt. JDBC Net Pure Java Driver
Hide Answer Workspace

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.

19) Which of the following is not a type of ResultSet object?

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.

• CONCUR_READ_ONLY: The ResultSet is read-only, this is the default concurrency type.


• CONCUR_UPDATABLE: We can use the ResultSet update method to update the rows
data.

20) What is JDBC Savepoint?

yyy. An intermediate or checkpoint in a transaction


zzz. A point where we can store queries
aaaa. A point where the JDBC application starts execution
bbbb. A memory where we can store transaction
Hide Answer Workspace

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:

• Register the driver


• Connecting to a database
• Preparing SQL statements in Java
• Executing the SQL statements on the database
• Retrieving the results
• Closing the connection

22) Which of the following is the correct to register a JdbcOdbcDriver?

gggg. jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();


hhhh. odbc.JdbcOdbcDriver obj = new sun.odbc.JdbcOdbcDriver();
iiii. jdbc.JdbcOdbcDriver obj = new sun.jdbc.JdbcOdbcDriver();
jjjj. jdbc.odbc.JdbcOdbc obj = new sun.jdbc.odbc.JdbcOdbc();
Hide Answer Workspace

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();

23) How many ways to register a driver?

kkkk. 2
llll. 3
mmmm. 4
nnnn. 5
Hide Answer Workspace

Answer: c

Explanation: There are four ways to register a driver:


1. By creating an object of the Driver For example:
sun.jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();
2. By sending the driver class object to the registerDriver() method of the DriverManager class.
For example:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
3. By sending the driver class name directly to the forName() For example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
4. By using the getProperty() method of the System class. For example:
String dname = System.getProperty("driver");
Class.forName(dname);
If you are using the above method to register the driver, we should have to specify the driver's
name at the time of running the program. The getProperty() method receives the driver name
and stores the driver name in dname.
We use the following command to provide the driver name at run time:
c:\> java -Ddriver = driverclassname Programname
For example:
c:\> java -Ddriver = sun.jdbc.odbc.JdbcOdbcDriver MyProgram

24) Identify the DSN in the following statement:

19. DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger")


oooo. jdbc
pppp. odbc
qqqq. scott
rrrr. oradsn
Hide Answer Workspace

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.?

ssss. getConnection("jdbc::thin@localhost:1521:oracle", "scott", "tiger");


tttt. getConnection("jdbc:thin@localhost:1521:oracle", "scott", "tiger");
uuuu. getConnection("jdbc::thin@localhost:1522:oracle", "scott", "tiger");
vvvv. getConnection("jdbc::oracle@localhost:1521:thin", "scott", "tiger");
Hide Answer Workspace

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");

26) What are the types of ResultSet in JDBC?

wwww. Forward ResultSet


xxxx. Scrollable ResultSet
yyyy. Only a
zzzz. Both a and b
Hide Answer Workspace

Answer: d
Explanation: JDBC provides only two types of ResultSets: Forward and Scrollable ResultSet.

27) What is blob in the following statement?

20. create table profilepic(photo blob);


aaaaa. Variable
bbbbb. Object
ccccc. Data type
ddddd. Keyword
Hide Answer Workspace

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.

29) DatabaseMetaData interface is used to get?????..?

iiiii. Comprehensive information about the database as a whole.


jjjjj. Comprehensive information about the table as a whole.
kkkkk. Comprehensive information about the column as a whole.
lllll. Both b and c
Hide Answer Workspace

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?

mmmmm. JDBC-ODBC Bridge Driver (Type 1)


nnnnn. Native API-partly Java Driver (Type 2)
ooooo. Net Protocol-pure Java Driver (Type 3)
ppppp. Native Protocol-pure Java Driver (Type 4)
Hide Answer Workspace

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.

31) Are ResultSets updateable?


qqqqq. Yes, but only if we call the method openCursor() on the ResultSet and if the driver
and database support this option.
rrrrr. Yes, but only if we indicate a concurrency strategy when executing the statement,
and if the driver and database support this option.
sssss. Yes, but only if the ResultSet is an object of class UpdateableResultSet and if the
driver and database support this option.
ttttt. No, ResultSets are never updateable. We must explicitly execute a DML statement
to change the data in the underlying database.
Hide Answer Workspace

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?

uuuuu. Statement Interface


vvvvv. ResultSet Interface
wwwww. Connection Interface
xxxxx. RowSet Interface
Hide Answer Workspace

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.

33) How many statement objects can be created using a Connection?

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.

35) Which statement(s) is/ are true about transactions?

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.

gggggg. Only i and ii


hhhhhh. Only i and iii
iiiiii. Only i, ii, and iv
jjjjjj. All the above
Hide Answer Workspace
Answer: c
Explanation: The statements i, ii, and iv are true about transactions but iii is not because the lock
mechanism prohibits two transactions from manipulating the same data at the same time.

You might also like