JDBC PDF
JDBC PDF
© Copyright by Interviewbit
Contents
Introduction to JDBC:
Components of JDBC:
There are four major components of JDBC using which it can interact with a
database. They are:
Scope of JDBC:
Earlier, ODBC API was used as the database API to connect with the database and
execute the queries. But, ODBC API uses C language for ODBC drivers(i.e. platform-
dependent and unsecured). Hence, Java has defined its own JDBC API that uses JDBC
drivers, which offers a natural Java interface for communicating with the database
through SQL. JDBC is required to provide a “pure Java” solution for the development
of an application using Java programming.
2. What is ResultSet?
JDBC driver of Oracle 10G is ojdbc14.jar and it can be obtained in the installation
directory of an Oracle at …/Oracle/app/oracle/product/10.2.0/server/jdbc/lib .
JDBC driver provides the connection to the database. Also, it implements the
protocol for sending the query and result between client and database.
6. Which data types are used for storing the image and file in
the database table?
BLOB data type is used to store the image in the database. We can also store
videos and audio by using the BLOB data type. It stores the binary type of data.
CLOB data type is used to store the file in the database. It stores the character
type of data.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`GET_EMP_DETAILS` $$
CREATE PROCEDURE `EMP`.`GET_EMP_DETAILS`
(IN EMP_ID INT, OUT EMP_DETAILS VARCHAR(255))
BEGIN
SELECT first INTO EMP_DETAILS
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Stored procedures are called using CallableStatement class available in JDBC API.
Below given code demonstrates this:
Three types of parameters are provided in the stored procedures. They are:
IN: It is used for passing the input values to the procedure. With the help of
setXXX() methods, you can bind values to IN parameters.
OUT: It is used for getting the value from the procedure. With the help of
getXXX() methods, you can obtain values from OUT parameters.
IN/OUT: It is used for passing the input values and obtaining the value
to/from the procedure. You bind variable values with the setXXX() methods
and obtain values with the getXXX() methods.
ODBC can be used for languages like JDBC is used only for the Java
C, C++, Java, etc. language
Most of the ODBC Drivers developed JDBC drivers are developed using
in native languages like C, C++ the Java language
10. What is Rowset?
A RowSet is an object that encapsulates a row set from either JDBC result sets or
tabular data sources such as files or spreadsheets. It supports component-based
development models like JavaBeans, with the help of a standard set of
properties and event notifications.
The advantages of using RowSet are:
It is easier and flexible to use.
It is Scrollable and Updatable by default.
ResultSet RowSet
ResultSet cannot
be serialized as it
RowSet is disconnected from the database so it
handles the
can be serialized.
connection to
the database.
By default,
ResultSet object
By default, the RowSet object is scrollable and
is non-scrollable
updatable.
and non-
updatable.
ResultSet object
is not a RowSet object is a JavaBean object.
JavaBean object.
ResultSet is
returned by the Rowset extends the ResultSet interface and it is
executeQuery() returned by calling the
method of RowSetProvider.newFactory().createJdbcRowSet()
Statement method.
interface
It is difficult to
pass ResultSet
from one class to It is easier to pass RowSet from one class to
another class as another class as it has no connection with the
it has a database.
connection with
the database.
Interfaces:
Statement st = conn.createStatement( );
ResultSet rs = st.executeQuery();
Statement PreparedStatement
Provides better
performance than
Performance is less compared
Statement, as it executes
to PreparedStatement.
the pre-compiled SQL
statements.
It is used to execute
the SQL statements
It can be
It is used to such as
used for any
execute SQL Insert/Update/Delete
SQL
Select queries. which will update or
statements.
modify the database
data.
It returns
the boolean
value TRUE It returns the It returns an integer
if the result ResultSet object value which
is a which contains represents the
ResultSet the data number of affected
object and retrieved by the rows where 0
FALSE when SELECT indicates that the
there is no statement. query returns null.
ResultSet
object.
Used for
executing
Used for
both Used for executing
executing only
SELECT and only a non-SELECT
the SELECT
non- query.
Query.
SELECT
queries.
The execute() method is used in the situations when you are not sure about the type
of statement else you can use executeQuery() or executeUpdate() method.
The above statement is used to retrieve the value of the specified column Index and
the return type is an int data type.
Setter Methods: These methods are used to set the value in the database. It is
almost similar to getter methods, but here it requires to pass the data/values for
the particular column to insert into the database and the column name or index
value of that column. Usually, setter method is represented as setXXX() methods.
Example:
void setInt(int Column_Index, int Data_Value)
The above statement is used to insert the value of the specified column Index with an
int value.
If two users are viewing the same record, then there is no issue, and locking will
not be done. If one user is updating a record and the second user also wants to
update the same record, in this situation, we are going to use locking so that
there will be no lost update.
Two types of locking are available in JDBC by which we can handle multiple user
issues using the record. They are:
Optimistic Locking: It will lock the record only when an update takes
place. This type of locking will not make use of exclusive locks when reading
or selecting the record.
Pessimistic Locking: It will lock the record as soon as it selects the row to
update. The strategy of this locking system guarantees that the changes are
made safely and consistently.
Dirty read implies the meaning “read the value which may or may not be
correct”. In the database, when a transaction is executing and changing some
field value, at the same time another transaction comes and reads the changed
field value before the first transaction could commit or rollback the value, which
may cause an invalid value for that particular field. This situation is known as a
dirty read.
Consider an example given below, where Transaction 2 changes a row but does
not commit the changes made. Then Transaction 1 reads the uncommitted
data. Now, if Transaction 2 goes for roll backing its changes (which is already
read by Transaction 1) or updates any changes to the database, then the view of
the data may be wrong in the records related to Transaction 1. But in this case,
no row exists that has an id of 100 and an age of 25.
Unable to load the appropriate JDBC drivers before calling the getConnection()
method.
It can specify an invalid or wrong JDBC URL, which cannot be recognized by the
JDBC driver.
This error may occur when one or more shared libraries required by the bridge
cannot be loaded.
Class.forName(“oracle.jdbc.driver.OracleDriver”);
The MySQL Connector/J version 8.0 library comes with a JDBC driver class:
com.mysql.jdbc.Driver. Before Java 6, we had to load the driver explicitly using the
statement given below:
Class.forName("com.mysql.jdbc.Driver");
However, this statement is no longer needed, because of a new update in JDBC 4.0
that comes from Java 6. As long as you place the MySQL JDBC driver JAR file into the
classpath of your program, the driver manager can find and load the driver.
: DriverManager is a built-in Java class with a
DriverManager.registerDriver()
static member register. Here we will be calling the constructor of the driver class
during compile time.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
DriverManager.registerDriver(new com.mysql.jdbc.Driver(); );
Here,
con: Reference to a Connection interface.
url: Uniform Resource Locator.
user: Username from which SQL command prompt is accessed.
password: Password from which SQL command prompt is accessed.
Url in Oracle can be created as follows:
Where oracle represents the database used, thin is the driver used, @localhost is the
IP(Internet Protocol) address where the database is stored, 1521 is the port number
and xe represents the service provider.
All 3 parameters given above are of string type and are expected to be declared by
the programmer before the function call. Use of this can be referred from the final
code of an application.
Where localhost represents hostname or IP address of the MySQL server, 3306 port
number of the server and by default, it is 3306, test1 is the name of the database on
the server.
Create a statement:
Once a connection establishment is done, you can interact with the database.
The Statement, PreparedStatement, and CallableStatement JDBC interfaces
will define the methods that permit you to send SQL commands and receive
data from the database.
We can use JDBC Statement as follows:
Statement st = con.createStatement();
Here, con is a reference to the Connection interface used in the earlier step.
Execute the query:
Here, query means an SQL query. We can have various types of queries. A few of
them are as follows:
Query for updating or inserting a table in a database.
Query for data retrieval.
The executeQuery() method that belongs to the Statement interface is used for
executing queries related to values retrieval from the database. This method
returns the ResultSet object which can be used to get all the table records.
The executeUpdate(sql_query) method of the Statement interface is used for
executing queries related to the update/insert operation.
Example:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("Data inserted successfully : "+sql);
else
System.out.println("Data insertion failed");
import java.sql.*;
import java.util.*;
class OracleCon
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String password = "123";
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("Data inserted successfully : "+sql);
else
System.out.println("Data insertion failed");
con.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
//Creating the connection
String url = "jdbc:mysql://localhost:3306/test1";
String user = "system";
String password = "123";
try
{
Class.forName("com.mysql.jdbc.Driver");
Statement st = con.createStatement();
cs.executeUpdate();
The sequence of actions (SQL statements) served as a single unit that is called a
transaction. Transaction Management places an important role in RDBMS-
oriented applications to maintain data consistency and integrity.
Transaction Management can be described well – by using ACID properties. ACID
stands for Atomicity, Consistency, Isolation, and Durability.
Atomicity - If all queries are successfully executed, then only data will be
committed to the database.
Consistency - It ensures bringing the database into a consistent state a er
any transaction.
Isolation - It ensures that the transaction is isolated from other
transactions.
Durability - If a transaction has been committed once, it will remain always
committed, even in the situation of errors, power loss, etc.
Need for Transaction Management:
When creating a connection to the database, the auto-commit mode will be
selected by default. This implies that every time when the request is executed, it
will be committed automatically upon completion.
We might want to commit the transaction a er the execution of few more SQL
statements. In such a situation, we must set the auto-commit value to False. So
that data will not be able to commit before executing all the queries. In case if
we get an exception in the transaction, we can rollback() changes made and
make it like before.
setAutoCommit() method:
The value of AutoCommit is set to TR
UE by default. A er the SQL statement execution, it will be committed
automatically. By using this method we can set the value for AutoCommit.
Syntax: conn.setAutoCommit(boolean_value)
Here, boolean_value is set to TRUE for enabling autocommit mode for the
connection, FALSE for disabling it.
Commit() method:
The commit() method is used for committing the data. A er the SQL statement
execution, we can call the commit() method. It will commit the changes made
by the SQL statement.
Syntax: conn.commit();
Rollback() method:
The rollback() method is used to undo the changes made till the last commit has
occurred. If we face any problem or exception in the SQL statements execution
flow, we may roll back the transaction.
Syntax: conn.rollback();
setSavepoint() method:
If you have set a savepoint in the transaction (a group of SQL statements), you
can use the rollback() method to undo all the changes till the savepoint or a er
the savepoint(), if something goes wrong within the current transaction. The
setSavepoint() method is used to create a new savepoint which refers to the
current state of the database within the transaction.
Syntax: Savepoint sp= conn.setSavepoint("MysavePoint")
releaseSavepoint() method:
It is used for deleting or releasing the created savepoint.
Syntax: conn.releaseSavepoint("MysavePoint");
The transaction isolation level is a value that decides the level at which
inconsistent data is permitted in a transaction, which means it represents the
degree of isolation of one transaction from another. A higher level of isolation
will result in improvement of data accuracy, but it might decrease the number of
concurrent transactions. Similarly, a lower level of isolation permits for more
concurrent transactions, but it reduces the data accuracy.
To ensure data integrity during transactions in JDBC, the DBMS make use of
locks to prevent access to other accesses to the data which is involved in the
transaction. Such locks are necessary for preventing Dirty Read, Non-Repeatable
Read, and Phantom-Read in the database.
It is used for the locking mechanism by DBMS and can be set using
setTransactionIsolation() method. You can obtain details about the level of
isolation used by the connection using getTransactionIsolation() method.
//import section
import java.sql.*;
import java.io.*;
public class CreateTableEx
{
public static void main(String[] args)throws Exception
{
//create an objet of buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//load and register the driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//establish a connection
Connection con = DriverManager.getConnection(“jdbc:odbc:nag”,”system”,”naveen”);
//create a statement object
Statement st = con.createStatement();
//receive dynamic input as a table name
System.out.println(“Enter table name”);
String tablename = br.readLine();
//execute SQL query
St.executeUpdate("create table"+tablename+"(empno number,empname varchar2(10),empsal
System.out.println(“Successfully created the table”);
//close the connection
con.close();
}
}
36. Conclusion
This article covers freshers to experienced level interview questions on JDBC. We
hope that this will give you an overview of JDBC interview questions. JDBC questions
are an important part of any Java interview, whether it is a core Java or Java EE
Interview. The explanations given in this article will enrich your knowledge and
increase your understanding of JDBC. All the Best…!!!
References:
“JDBC API Tutorial and Reference” by Fisher, Maydene-Ellis, Jon-Bruce, Jonathan.
“FROM ZERO TO JDBC HERO” by Vivian Siahaan, Rismon Hasiholan Sianipar.
“JDBC Pocket Reference” by Donald Bales.
https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html
https://www.youtube.com/playlist?list=PLsyeobzWxl7rU7Jz3zDRpqB-EODzBbHOI
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions