JDBC
JDBC
JDBC
A: JDBC stands for Java Database Connectivity, which is a standard Java API for databaseindependent connectivity between the Java programming language and a wide range of
databases.
Q: Describe a general JDBC Architecture.
A: General JDBC Architecture consists of two layers: JDBC API (This provides the
application-to-JDBC Manager connection) and JDBC Driver API (This supports the JDBC
Manager-to-Driver Connection).
Q: What are the common JDBC API components?
A: JDBC API consists of following interfaces and classes: DriverManager, Driver, Connection,
Statement, ResultSet, SQLException.
Q: What is a JDBC DriverManager?
A: JDBC DriverManager is a class that manages 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 JDBC Driver?
A: JDBC driver is an interface enabling a Java application to interact with a database. To
connect with individual databases, JDBC requires drivers for each database. The JDBC driver
gives out the connection to the database and implements the protocol for transferring the query
and result between client and database
Q: What is a connection?
A: Connection interface consists of methods for contacting a database. The 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: These 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 through its data. The
java.sql.ResultSet interface represents the result set of a database query.
Q: What are types of ResultSet?
A: There are three constants which when defined in result set can move cursor in resultset
backward, forward and also in a particular row.
1. ResultSet.TYPE_FORWARD_ONLY: The cursor can only move forward in the result
set.
2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can scroll forwards and
backwards, and the result set is not sensitive to changes made by others to the database
that occur after the result set was created.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
Q: Which type of JDBC driver is the fastest one?
A: 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.
Q: Does the JDBC-ODBC Bridge support multiple concurrent open statements per
connection?
A: No. You can open only one Statement object per connection when you are using the JDBCODBC Bridge.
Q: What are the standard isolation levels defined by JDBC?
A: The standard isolation levels are:
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
Q: What is the design pattern followed by JDBC?
A: JDBC architecture decouples an abstraction from its implementation. Hence 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.
Q: What are the different types of JDBC Statements?
A: Types of statements are:
Statement (regular SQL statement)
PreparedStatement (more efficient than statement due to pre-compilation of SQL)
CallableStatement (to call stored procedures on the database)
Q: What is difference 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 arguments rather than creating a new execution plan
every time. Prepared statements use bind arguments, which are sent to the database engine. This
allows mapping different requests with same prepared statement but different arguments to
execute the same execution plan. Prepared statements are more secure because they use bind
variables, which can prevent SQL injection attack.
enhancements.
New
methods
added
to
Q: Out of String or a java.sql.Clob, which has best performance 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 go
back 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 class, does it mean it imports the driver
class using import statement?
A: No, it doesn't. An import statement tells the compiler which class to look for.
Class.forName() instructs the Classclass to find a class-loader and load that particular Class
object into the memory used by the JVM.
Q: What we set the attribute Concurrency in ResultSet?
A: The 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_UPDATABLE : means that the ResultSet can be both read and
updated.
Q: What are the differences between setMaxRows(int) and SetFetchSize(int)?
A: 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.
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.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:SampleExcel","","");
stmt=conn.createStatement();
Due to failing to load the appropriate JDBC drivers before calling the getConnection
method.
It can be specifying an invalid JDBC URL, one that is not recognized by JDBC driver.
This error can occur if one or more the shared libraries needed by the bridge cannot be
loaded
setAutoCommit() allowed us to commit the transaction commit state manually the default values
of the setAutoCommit() is true.
Why Prepared Statements are faster?
Prepared execution is faster than direct execution for statements executed more than three or four
times because the statement is compiled only once. Prepared statements and JDBC driver are
linked with each other. We can bind drivers with columns by triggering the query into the
database. When we execute Connection.prepareStatement(), all the columns bindings take place,
in oder to reduce the time.
What restrictions are placed on method overriding?
The restriction on method overloading is the signature of the method.
The signature is the number, type, and order of the arguments passed to a method.
Overridden methods must have the same name, argument list, and return type.
Any method which has the same name cannot have the same signature.
They can have the same return types in the same scope.
The compiler uses the signature to detect which overloaded method to refer when a
overloaded method is called.
If two methods have the same name and signature the compiler will throw a runtime
error.
JDBC/ODBC: These require an ODBC (Open Database Connectivity) driver for the
database to be installed. It is used for local connection.
Native API (partly-Java driver): This type of driver uses a database API to interact with
the database. It also provides no host redirection.
Network Protocol Driver: It makes use of a middle-tier between the calling program
and the database. The client driver communicates with the net server using a databaseindependent protocol and the net server translates this protocol into database calls.
Native Protocol Drive: This has a same configuration as a type 3 driver but uses a wire
protocol specific to a particular vendor and hence can access only that vendor's database.
Is it possible to connect to multiple databases simultaneously? Using single statement can one
update or extract data from multiple databases?
Yes, it is possible but it depends upon the capabilities of the specific driver implementation, we
can connect to multiple databases at the same time. We doing following steps:
Minimum one driver will be used to handle the commits transaction for multiple
connections.
To update and extract data from the different database we use single statement for this we
need special middleware to deal with multiple databases in a single statement or to
effectively treat them as one database.
setFetchSize(int) defines the number of rows that will be read from the database when the
ResultSet needs more rows whereas setMaxRows(int) method of the ResultSet specifies
how many rows a ResultSet can contain at a time.
In setFetchSize(int), method in the java.sql.Statement interface will set the 'default' value
for all the ResultSet derived from that Statement whereas in setMaxRow(int) default
value is 0, i.e. all rows will be included in the ResultSet.
the setMaxRows affects the client side JDBC object while the setFetchSize affects how
the database returns the ResultSet data.
It can be used to make a ResultSet object scrollable and updatable. All RowSet objects
are by default scrollable and updatable.
Load the RDBMS specific JDBC driver because this driver actually communicates with
the database.
Open the connection to database, for sending SQL statements and get results back.
Execute statement which returns result set. ResultSet contains the tuples of database table
as a result of SQL query.
I have the choice of manipulating database data using a byte[] or a java.sql.Blob. Which has best
performance?
We use java.sql.Blob, because of following reason:
It does not extract any data from the database until we trigger a query to the databse.
We use byte[] for inserting data in the database when data is not upload in the database
till yet.
Data Manipulation Language (DDL) this portion of the SQL standard is concerned with
manipulating the data in a database as opposed to the structure of a database. The DML deals
with the SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.
Data Definition Language (DDL) this portion of the SQL standard is concerned with the
creation, deletion and modification of database objects like tables, indexes and views. The core
verbs for DDL are CREATE, ALTER and DROP. While most DBMS engines allow DDL to be
used dynamically, it is often not supported in transactions.
How can you load the drivers?
It is very simple and involves just one line of code to load the driver or drivers we want to use.
For example, We want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Driver documentation will give you the class name to use. For instance, if the class name is
jdbc.DriverHELLO, you would load the driver with the following line of code:
Class.forName(jdbc.DriverHELLO);
How do I insert an image file (or other raw data) into a database?
All raw data types should be read and uploaded to the database as an array of bytes, byte[].
By using the Database Specific JDBC drivers, it interacts with a database without the
applications of RDBMS.
2. Name the new features added in JDBC 4.0.
The major features introduced in JDBC 4.0 are :
Auto-loading by JDBC driver class.
Enhanced Connection management
RowId SQL enabled.
DataSet implemented by SQL by using Annotations
Enhancements of SQL exception handling
Supporting SQL XML files.
3. How do Java applications access the database using JDBC?
Java applications access the database using JDBC by :
Communicating with the database for Loading the RDBMS specific JDBC driver
Opening the connection with database
Sending the SQL statements and get the results back.
Creating JDBC Statement object which contains SQL query.
Executing statement to return the resultset(s) containing the tuples of database table which is a
result of SQL query.
Processing the result set.
Closing the connection.
4. Briefly tell about the JDBC Architecture.
The JDBC Architecture consists of two layers:
1.The JDBC API
2.The JDBC Driver API
The JDBC API provides the application-JDBC Manager connection.
After compilation, prepared statements may be customized before every execution by the
alteration of predefined SQL parameters.
Code:
PreparedStatement pstmt = conn.prepareStatement("UPDATE data= ? WHERE vl = ?");
pstmt.setBigDecimal(1, 1200.00);
pstmt.setInt(2, 192);
12. Differentiate between a Statement and a PreparedStatement.
A standard Statement is used for creating a Java representation for a literal SQL statement and
for executing it on the database.
A PreparedStatement is a precompiled Statement.
A Statement has to verify its metadata in the database every time.
But ,the prepared statement has to verify its metadata in the database only once.
If we execute the SQL statement, it will go to the STATEMENT.
But, if we want to execute a single SQL statement for the multiple number of times, itll go to
the PreparedStatement.
13. What is the function of setAutoCommit?
When a connection is created, it is in auto-commit mode.
This means that each individual SQL statement is to be treated as a single transaction .
The setAutoCommit will be automatically committed just after getting executed.
The way by which two or more statements are clubbed into a transaction to disable the autocommit mode is :
con.setAutoCommit (false);
Once auto-commit mode is disabled, no SQL statements will be committed until we call the
method commit explicitly.
Code :
con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEE SALES = ?
WHERE COF_NAME LIKE ?");
The ResultSet constants for specifying whether a resultset is read-only or updatable are:
- CONCUR_READ_ONLY
- CONCUR_UPDATABLE.
18. How do we load the drivers?
To Load the driver or drivers we need to use a very simple one line of code.
If we want to use the JDBC/ODBC Bridge driver, the following code will load it:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
The driver documentation gives the class name to use.
For example, if the class name is jdbc.DriverXYZ, we can load the driver using the below line
of code:
Code:
Class.forName(jdbc.DriverXYZ);
19. What Class.forName does, while loading the drivers?
It is used for creating an instance of a driver
It is used for registering with theDriverManager.
When we have loaded a driver, it connects with the DBMS.
20. How can you make a connection?
To establish a connection we need to have an appropriate driver, connected to the DBMS.
The below line of code illustrates the idea:
Code:
String url = jdbc:odbc: rima;
Connection con = DriverManager.getConnection(url, rima, J8?);
1. What are the factors that the JDBC driver performance depends on?
The JDBC driver performance depends on:
Type 2: Native type API (partly-Java driver)This type of driver uses a vendor-specific driver
or database API for interacting with the database. An example of such an API is Oracle OCI
(Oracle Call Interface).
Type 3: Open Net Protocol This is vendor non-specific and works by forwarding database
requests using a net server component. The net server accesses the database. The client driver
connects with the server using a database-indifferent protocol and the server translates this
protocol into database calls.
Type 4: Proprietary Protocol-Net(pure Java driver)This is same as per configuration as type 3
driver while it uses a wire protocol directed towards a particular vendor and so it can access only
that vendor's database.
5. Explain how to Make Updates to the Updatable ResultSets.
The JDBC 2.0 API can update rows in a ResultSet using the methods in the Java rather than
using a SQL command.
But before doing that, we create a ResultSet object which is updatable.
For doing this, we give the ResultSet CONCUR_UPDATABLE in the createStatement method.
Code:
Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
stmt.executeQuery("SELECT COF_NAME, PRICE ");
6.What are the utilities of the callable statements?
Callable statements are mainly used in the JDBC applications.
Callable statements are used to invoke stored procedures
This is mainly used in functions.
7. Differentiate between TYPE_SCROLL_INSENSITIVE and
TYPE_SCROLL_SENSITIVE.
We will get a scrollable ResultSet object if we specify either one of the ResultSet constants.
The difference between the two depends on, whether a resultset is showing fv changes or not.
This difference depends on certain methods which are called to detect changes or not.
The resultset TYPE_SCROLL_INSENSITIVE does not show the change to it but the ResultSet
srs = TYPE_SCROLL_SENSITIVE will show the change.
The following code explains the difference :
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price 1= srs.getFloat("PRICE");
System.out.println(name + " " + price1);
}
8. How JDBC Statements are used?
A Statement is an object, by which we send an SQL statement to the DBMS.
We create a Statement object and then execute it.
For a SELECT Statement, the method used is executeQuery.
The Statement that creates or modifies a table is executeUpdate.
For creating a Statement object an instance of an active connection is required.
In the following code, we use our Connection object con to create the Statement object
Statement stmt = con . createStatement();
9. How can we retrieve data from the ResultSet?
What
is
JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides crossDBMS connectivity to a wide range of SQL databases and access to other tabular data sources,
such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all
corporate
data
even
in
a
heterogeneous
environment
2.
What
are
stored
procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored
procedure is precompiled. Each Database has it's own stored procedure language,
Read
Also
Types
3.
by
What
of
JDBC
is
Driver
JDBC
explained
with
Driver
Example
?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided
the JDBC API. This driver is used to connect to the database.
4.
What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to
register this driver with DriverManager class. Then we can open a connection. By using this
connection , we can create a statement object and this object will help us to execute the query.
5.
What
is
DriverManager
?
DriverManager is a class in java.sql package. It is the basic service for managing a set of
JDBC
drivers.
6.
What
is
a
ResultSet
?
A table of data representing a database result set, which is usually generated by executing a
statement
that
queries
the
database.
ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is
positioned before the first row. The next method moves the cursor to the next row, and because
it returns false when there are no more rows in the ResultSet object, it can be used in a while
loop
to
iterate
through
the
result
set.
7.
What
is
Connection?
Connection class represents a connection (session) with a specific database. SQL statements
are executed and results are returned within the context of a connection.
Connection object's database is able to provide information describing its tables, its supported
SQL grammar, its stored procedures, the capabilities of this connection, and so on. This
information
is
obtained
with
the
getMetaData
method.
8.
A
What
class
does
as
loaded
Class.forName
by
the
return?
classloader.
9.
What
is
Connection
pooling?
Connection pooling is a technique used for sharing server resources among requesting clients.
Connection pooling increases the performance of Web applications by reusing active database
connections instead of creating a new connection with every request. Connection pool manager
maintains
a
pool
of
open
database
connections.
10. What
There
are
are
the
mainly four
different
JDB
drivers
type of JDBC drivers available.
available?
They are:
Type 1 : JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via
one or more ODBC drivers. Note that some ODBC native code and in many cases native
database client code must be loaded on each client machine that uses this type of driver. Hence,
this kind of driver is generally most appropriate when automatic installation and downloading
of a Java technology application is not important. For information on the JDBC-ODBC bridge
driver
provided
by
Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver
converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other
DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be
loaded
on
each
client
machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates
JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS
protocol by a server. This net server middleware is able to connect all of its Java technologybased clients to many different databases. The specific protocol used depends on the vendor. In
general, this is the most flexible JDBC API alternative. It is likely that all vendors of this
solution will provide products suitable for Intranet use. In order for these products to also
support Internet access they must handle the additional requirements for security, access
through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technologybased
drivers
to
their
existing
database
middleware
products.
Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver
converts JDBC technology calls into the network protocol used by DBMSs directly. This allows
a direct call from the client machine to the DBMS server and is a practical solution for Intranet
access. Since many of these protocols are proprietary the database vendors themselves will be
the primary source for this style of driver. Several database vendors have these in progress.
11.
What
is
the
fastest
type
of
JDBC
driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers
will be slower than Type 2 drivers (the database calls are make at least three translations versus
two),
and
Type
4
drivers
are
the
fastest
(only
one
translation).
12.
Is
the
JDBC-ODBC
Bridge
multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge
uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded
Java programs may use the Bridge, but they won't get the advantages of multi-threading.
13. What
is
cold
backup,
hot
backup,
warm
backup
recovery?
Cold backup means all these files must be backed up at the same time, before the database is
restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace
while the database is running and is being accessed by the users
14.
What
is
the
advantage
of
denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving
performance. It maybe efficient for a high-throughput system to replicate data for certain data.
15.
How
do
you
handle
your
own
transaction
?
Connection Object has a method called setAutocommit ( boolean flag) . For handling our own
transaction we can set the parameter to false and begin your transaction . Finally commit the
transaction by calling the commit method.
Question 1 : Difference between SQL Date and java.util.Date in Java
Answer : This is one of JDBC Questions which I like to ask, because knowing how to correctly store and retrieve date
in a database is often confusing for new developers and its very critical for any application. Main difference between
SQL data i.e.java.sql.Date and util date i.e. java.util.Date is that SQL Date only contains date part and not
time part but util date contains both date and time part. See SQL Date vs Util Date in Java for more differences
between them.
Question 2: What is benefit of using PreparedStatement in Java
Answer : Another wonderful JDBC interview question which is very popular on telephonic as well as on early round of
Java Interviews. There are several benefits of using PreparedStatement while querying database from Java
program e.g. better performance and prevents from SQL Injection. I suggest to read Why use PreparedStatement in
Java for more benefits and details on JDBC PreparedStatement.
Question 3: What is JDBC database Connection Pool? How to setup in Java?
Answer : I have always seen at least one question related to database connection pool in JDBC Interview e.g. benefit
of using JDBC Connection pool. Well JDBC connection pool maintains pool of JDBC connection which is used by
application to query database. Since JDBC connection are expensive it take time to create them which can slow
response time of server if created during request time. Creating them on application start-up and reusing them result
in better performance. See How to setup JDBC Connection Pool in Java using Spring for more details on JDBC
connection pool and benefits it offer.
Question 4: What is difference between type 2 and type 4 JDBC drivers in Java
Answer : This JDBC Interview question is as old as Vector vs ArrayList or Hashtable vs HashMap. I remember
questions about JDBC ODBC drivers asked during almost every fresher level interview. Key difference between type
2 and type 4 JDBC driver is that you just need to include JAR file of JDBC driver in your classpath to connect
database. See this link for more difference between type 2 and type 4 JDBC drivers.
Question 5: What is difference between java.sql.Time and java.sql.TimeStamp in Java
Answer : This JDBC questions is similar to earlier JDBC interview question java.sql.Date vs java.util.Date.
Main difference is that java.sql.Time class doesn't contain any date information on it
while java.sql.TimeStamp contains date information. See 4 difference between Time and Timestamp in Java
JDBC for more differences.
Question 6: What happens if we call resultSet.getInt(0) when Select query result just have one column
of integer type?
Answer : This is one of the tricky Java question which comes from JDBC. you may think that it will return first column
as integer from Query result set but unfortunately it doesn't. It throws InvalidColumnIndexException in JDBC
because index forgetXXX() or setXXX() in JDBC starts with 1. See How to fix InvalidColumnIndexException in
JDBC for more details on this JDBC interview question.
Question 7: What is difference between RowSet and ResultSet in JDBC?
Answer : One of the popular JDBC interview question now days. RowSet extends ResultSet and add support for
JDBC API to Java bean component model. Main difference of ResultSet and RowSet is RowSet being connected
and disconnected, which is another follow-up JDBC question. RowSet makes it easy to use ResultSet but as I said
you only like to use it to get benefit of disconnected and connected RowSet.
Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is
automatically loaded).
Open the connection to database which is then used to send SQL statements and get results back.
Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The
JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting
multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC
drivers and the Java application is shown in Figure 1.
DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper
database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded,
the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object represents communication context,
i.e., all communication with database is through connection object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.
Driver layer consists of DriverManager class and the available JDBC drivers.
The application begins with requesting the DriverManager for the connection.
An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which
falls under the application layer.
The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend
and obtain the results.
10.What is Statement ?
Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of
objects.
Through the connection object we create statement kind of objects.
Statement stmt
= conn.createStatement();
11.What is PreparedStatement?
A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve
the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once
compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.
PreparedStatement
Statement has to verify its metadata against the database every time.
While a prepared statement has to verify its metadata against the database
only once.
Type 1: JDBC/ODBCThese require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of
driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly
to the ODBC driver. It provides no host redirection capability.
Type2: Native API (partly-Java driver)This type of driver uses a vendor-specific driver or database API to interact with the
database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.
Type 3: Open Protocol-NetThis is not vendor specific and works by forwarding database requests to a remote database
source using a net server component. How the net server component accesses the database is transparent to the client. The
client driver communicates with the net server using a database-independent protocol and the net server translates this
protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)This has a same configuration as a type 3 driver but uses a wire protocol
specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.