2160707
Advanced Java
Unit-2
JDBC Programming
Prof. Swati R. Sharma
[email protected]Unit-2 JDBC Programming 1 Darshan Institute of Engineering & Technology
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10
Reference Book:
Complete Reference J2EE by James Keogh mcgraw publication
Chapter : 6 and 7
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 3 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 4 Darshan Institute of Engineering & Technology
Introduction
Database
• Collection of data
DBMS
• Database Management System
• Storing and organizing data
SQL
• Relational database
• Structured Query Language
JDBC
• Java Database Connectivity
• JDBC driver
Unit-2 JDBC Programming 5 Darshan Institute of Engineering & Technology
Introduction: JDBC
JDBC (Java Database Connectivity) is used to It provides classes and interfaces
connect java application with database. to connect or communicate Java
application with database.
JDBC is an API used to
communicate Java application to
database in database independent
and platform independent
manner.
Example
Oracle
MS Access
My SQL
SQL Server
..
.
Unit-2 JDBC Programming 6 Darshan Institute of Engineering & Technology
Introduction: JDBC
JDBC (Java Database Connection) is the standard method of
accessing databases from Java application.
JDBC is a specification from Sun Microsystem that provides a
standard API for java application to communicate with different
database.
JDBC is a platform independent interface between relational
database and java applications.
Unit-2 JDBC Programming 7 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 8 Darshan Institute of Engineering & Technology
What is an API?
Application Program Interface
A set of routines, protocols, and tools for building software
applications.
JDBC is an API, which is used in java programming for interacting
with database.
Unit-2 JDBC Programming 9 Darshan Institute of Engineering & Technology
Introduction: JDBC API
JDBC API allows java programs to
i. Make a connection with database
ii. Creating SQL statements
Java Application
iii. Execute SQL statement
Java DB API
iv. Viewing
1. Open a&Connection
Modifying the resulting records
2. Send a statement
DBMS Engine
3. Retrieve results
4. Close a connection 1. Create a connection
Session
2. Execute statement
3. Send results
4. Close the session
Unit-2 JDBC Programming 10 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 11 Darshan Institute of Engineering & Technology
The JDBC Connectivity Model
JDBC API
JAVA
JDBC Driver
Application Database
Unit-2 JDBC Programming 12 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 13 Darshan Institute of Engineering & Technology
JDBC Architecture
It provides classes & interfaces A Java program that runs stand
Java Application alone in a client or server.
to connect or communicate
Java application with database.
JDBC API This class manages a list of
This interface handles the database drivers.
communications with the It ensures that the correct
database driver is used to access each
JDBC Driver data source.
Manager
JDBC Driver JDBC Driver JDBC Driver
Database is a
collection of
organized
information
ODBC Data
Oracle SQL Server Source
Unit-2 JDBC Programming Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 15 Darshan Institute of Engineering & Technology
JDBC Driver
API: Set of interfaces independent of the RDBMS
Driver: RDBMS-specific implementation of API interfaces
e.g. Oracle, DB2, MySQL, etc.
Just like Java aims for “Write once, Run anywhere",
JDBC strives for “Write once, Run with any database".
Unit-2 JDBC Programming 16 Darshan Institute of Engineering & Technology
JDBC Driver: Type1 (JDBC-ODBC Driver)
Depends on support for ODBC
Not portable
Translate JDBC calls into ODBC calls and use Windows ODBC built in
drivers
ODBC must be set up on every client
• for server side servlets ODBC must be set up on web server
driver sun.jdbc.odbc.JdbcOdbc provided by JavaSoft with JDK
No support from JDK 1.8 (Java 8)
E.g. MS Access
Unit-2 JDBC Programming 17 Darshan Institute of Engineering & Technology
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Local Computer
Java Application
DB Vendor
Application Code Driver
Type 1
ODBC Local
JDBC ODBC Bridge
Driver
DBMS
Vendor Specific Protocol Network Communication
Database Server
Unit-2 JDBC Programming 18 Darshan Institute of Engineering & Technology
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Advantages :
Allow to communicate with all database supported by ODBC driver
It is vendor independent driver
Disadvantages:
Due to large number of translations, execution speed is decreased
Dependent on the ODBC driver
ODBC binary code or ODBC client library to be installed in every client
machine
Uses java native interface to make ODBC call
Because of listed disadvantage, type1 driver is not used in production
environment. It can only be used, when database doesn’t have any other
JDBC driver implementation.
Unit-2 JDBC Programming 19 Darshan Institute of Engineering & Technology
JDBC Driver: Type 2 (Native Code Driver)
JDBC API calls are converted into native API calls, which are
unique to the database.
These drivers are typically provided by the database vendors and
used in the same manner as the JDBC-ODBC Bridge.
Native code Driver are usually written in C, C++.
The vendor-specific driver must be installed on each client
machine.
Type 2 Driver is suitable to use with server side applications.
E.g. Oracle OCI driver, Weblogic OCI driver, Type2 for Sybase
Unit-2 JDBC Programming 20 Darshan Institute of Engineering & Technology
JDBC Driver: Type 2 (Native Code Driver)
Local Computer
Java Application
DB Vendor Driver
Application Code
Type 2
Native API Local
DBMS
Vendor Specific Protocol Network Communication
Database Server
Unit-2 JDBC Programming 21 Darshan Institute of Engineering & Technology
JDBC Driver: Type 2 (Native Code Driver)
Advantages
As there is no implementation of JDBC-ODBC bridge, it may be
considerably faster than a Type 1 driver.
Disadvantages
The vendor client library needs to be installed on the client
machine.
This driver is platform dependent.
This driver supports all java applications except applets.
It may increase cost of application, if it needs to run on different
platform (since we may require buying the native libraries for all of
the platform).
Unit-2 JDBC Programming 22 Darshan Institute of Engineering & Technology
JDBC Driver: Type 3 (Java Protocol)
Pure Java Driver
Depends on Middleware server
Can interface to multiple databases – Not vendor specific.
Follows a three-tier communication approach.
The JDBC clients use standard network sockets to communicate
with a middleware application server.
The socket information is then translated by the middleware
application server into the call format required by the DBMS.
This kind of driver is extremely flexible, since it requires no code
installed on the client and a single driver can actually provide
access to multiple databases.
Unit-2 JDBC Programming 23 Darshan Institute of Engineering & Technology
JDBC Driver: Type 3 (Java Protocol)
Local Computer Middleware Server
Java Application JDBC Type 1 Driver
Application Code
JDBC Type 2 Driver
Type 3
JDBC-Net pure Java JDBC Type 4 Driver
Vendor Specific Protocol Network Communication
Database Server
Unit-2 JDBC Programming 24 Darshan Institute of Engineering & Technology
JDBC Driver: Type 3 (Java Protocol)
Advantages
Since the communication between client and the middleware
server is database independent, there is no need for the database
vendor library on the client.
A single driver can handle any database, provided the middleware
supports it.
We can switch from one database to other without changing the
client-side driver class, by just changing configurations of
middleware server.
E.g.: IDS Driver, Weblogic RMI Driver
Unit-2 JDBC Programming 25 Darshan Institute of Engineering & Technology
JDBC Driver: Type 3 (Java Protocol)
Disadvantages
Compared to Type 2 drivers, Type 3 drivers are slow due to
increased number of network calls.
Requires database-specific coding to be done in the middle tier.
The middleware layer added may result in additional latency, but
is typically overcome by using better middleware services.
Unit-2 JDBC Programming 26 Darshan Institute of Engineering & Technology
JDBC Driver: Type 4 (Database Protocol)
It is known as the Direct to Database Pure Java Driver
Need to download a new driver for each database engine
e.g. Oracle, MySQL
Type 4 driver, a pure Java-based driver communicates directly with
the vendor's database through socket connection.
This kind of driver is extremely flexible, you don't need to install
special software on the client or server.
Such drivers are implemented by DBMS vendors.
Unit-2 JDBC Programming 27 Darshan Institute of Engineering & Technology
JDBC Driver: Type 4 (Database Protocol)
Local Computer
Java Application
Application Code
Type 4
100% Pure Java Local
DBMS
Vendor Specific Protocol Network Communication
Database Server
Unit-2 JDBC Programming 28 Darshan Institute of Engineering & Technology
JDBC Driver: Type 4 (Database Protocol)
Advantages
Completely implemented in Java to achieve platform independence.
No native libraries are required to be installed in client machine.
These drivers don't translate the requests into an intermediary format (such
as ODBC).
Secure to use since, it uses database server specific protocol.
The client application connects directly to the database server.
No translation or middleware layers are used, improving performance.
The JVM manages all the aspects of the application-to-database
connection.
Disadvantage
This Driver uses database specific protocol and it is DBMS vendor
dependent.
Unit-2 JDBC Programming 29 Darshan Institute of Engineering & Technology
JDBC Driver
Thin Driver You can connect to a database without the client installed on your
machine. E.g. Type 4.
Thick Driver Thick client would need the client installation.
E.g. Type 1 and Type 2.
Unit-2 JDBC Programming 30 Darshan Institute of Engineering & Technology
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Name: JDBC-ODBC Native Code Java Protocol/ Database Protocol
Bridge Driver/ JNI Middleware
Vendor No Yes No Yes
Specific:
Portable No No Yes Yes
Pure No No Yes Yes
Java
Driver
Working JDBC-> ODBC JDBC call -> native JDBC call -> JDBC call ->DB
call specific call middleware specific call
ODBC -> native specific.
call Middleware ->
native call
Multiple Yes No Yes No
DB [only ODBC [DB Driver should
supported DB] be in middleware]
Unit-2 JDBC Programming 31 Darshan Institute of Engineering & Technology
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Name: JDBC-ODBC Native Code Java Protocol/ Database Protocol
Bridge Driver/ JNI Middleware
Example MS Access Oracle OCI driver IDA Server MySQL
Executio Slowest among Faster Compared Slower Compared Fastest among all
n Speed all to Type1 to Type2
Driver Thick Driver Thick Driver Thin Driver Thin Driver
Unit-2 JDBC Programming 32 Darshan Institute of Engineering & Technology
Which Driver should be Used?
If you are accessing one type of database such as MySql, Oracle,
Sybase or IBM etc., the preferred driver type is 4.
If your Java application is accessing multiple types of databases at
the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4
driver is not available yet for your database.
The type 1 driver is not considered a deployment-level driver, and
is typically used for development and testing purposes only.
Unit-2 JDBC Programming 33 Darshan Institute of Engineering & Technology
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLServ jdbc:microsoft:sqlserver:
erDriver //hostname:1433;DatabaseName
Unit-2 JDBC Programming 34 Darshan Institute of Engineering & Technology
JDBC Driver: Reference Link
Type 1: https://www.youtube.com/watch?v=np3TQe9mE0o
Type 2:
https://www.youtube.com/watch?v=9L7BRUTxbu8&list=PLmCsXD
GbJHdjvpGcahcNlV9-moRmJqWDs&index=3
Type 3:
https://www.youtube.com/watch?v=yd4nFHkCe2Q&list=PLmCsXD
GbJHdjvpGcahcNlV9-moRmJqWDs&index=4
Type 4:
https://www.youtube.com/watch?v=qlu5cx15fmk&list=PLmCsXDG
bJHdjvpGcahcNlV9-moRmJqWDs&index=5
Unit-2 JDBC Programming 35 Darshan Institute of Engineering & Technology
GTU Question : JDBC
1 What is JDBC? List out all various types of JDBC Driver. Explain Sum’16
Thick and Thin driver. Write code snippet for each type of JDBC
connection. Comment on selection of driver. [7 Marks]
2 What is JDBC? Explain the types of JDBC drivers? Write a code Win’16
snippet for each type of JDBC connection. [7 Marks]
3 Explain JDBC driver types in detail.[7 Marks] Sum’17
4 List the different types of JDBC drivers. Compare the various Sum’18
driver types for their advantages and disadvantages.
5 List different types of JDBC drivers and explain any two of them. Win’18
[7 Marks]
6 List types of diver used in JDBC. Explain Thin driver. [3 Marks] Win’19
Unit-2 JDBC Programming 36 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 37 Darshan Institute of Engineering & Technology
JDBC Components
The JDBC API provides the following interfaces and classes
Package java.sql
Class
It acts as an interface between user and
DriverManager
drivers. It keeps track of the drivers that
are available and handles establishing a
This
connectioninterface handles and the
between a database the
Driver
communications
appropriate driver. with the database
server. Driver interface provides vendor-
specific
This implementations
Interface of between
is the session the abstract
java
Interface
Connection
classes provided
application and by the JDBCItAPI.
database. contains all
methods for contacting a database.
Statement This interface is used to submit the SQL
statements to the database.
These objects hold data retrieved from a
ResultSet database after you execute an SQL query
using Statement objects. It acts as an
Exception
iterator to allow you to move through its
SQLException This
data.class handles any errors that occur in a
database application.
Unit-2 JDBC Programming 38 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 39 Darshan Institute of Engineering & Technology
JDBC Package
java.sql
Contains core java objects of JDBC API.
It includes java data objects, that provides basics for connecting to
DBMS and interacting with data stored in DBMS.
This package performs JDBC core operations such as Creating and
Executing query.
Unit-2 JDBC Programming 40 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 41 Darshan Institute of Engineering & Technology
JDBC Process
Step 1: Loading JDBC Driver
Step 2: Connection to DBMS
Step 3: Creating and executing statement
Step 4: Processing data returned by the DBMS
Step 5: Terminating Connection with DBMS
Unit-2 JDBC Programming 42 Darshan Institute of Engineering & Technology
Step 1: Loading JDBC Driver
Create an instance of the driver
Register driver in the driver manager
Loading the driver or drivers
for example, you want to use driver for mysql, the following code
will load it: Returns the Class object associated with the
class or interface with the given string name.
Class.forName("com.mysql.jdbc.Driver”);
Class that represent Main Pakage
classes
Class.forName() is
and interfaces in used It is used to initiate
a forrunning
loading class Java
dynamically Driver at runtime
Sub-Pakage
application.
Unit-2 JDBC Programming 43 Darshan Institute of Engineering & Technology
Step 2: Connection to DBMS
After you've loaded the driver, you can establish a connection
using the DriverManager class (java.sql.DriverManager).
Method: DriverManager
public static Connection Attempts to establish a connection to the given
getConnection(String url) database URL. The DriverManager attempts to
throws SQLException select an appropriate driver from the set of
registered JDBC drivers.
public static Connection Attempts to establish a connection to the given
getConnection(String url, database URL.
String user, url - a database url of the
String password form jdbc:subprotocol:subname
user - the database user on whose behalf the
) connection is being made
throws SQLException password - the user's password
Unit-2 JDBC Programming 44 Darshan Institute of Engineering & Technology
Step 2: Connection to DBMS
Syntax:
Interface of java.sql package
Connection conn=
DriverManager.getConnection(URL,USER_NM,PASS)
;Class of java.sql package
Example:
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu","root", "pwd");
Database Name
Unit-2 JDBC Programming 45 Darshan Institute of Engineering & Technology
Step 3: Creating statement
Once a connection is obtained, we can interact with the database.
The JDBC Statement interfaces define the methods and properties
that enable you to send SQL or PL/SQL commands and receive
data from your database.
Statement st=con.createStatement();
Interface is used for general- Statement createStatement()
purpose access to your database, throws SQLException
when using static SQL statements at Creates a Statement object for sending
runtime. SQL statements to the database.
Unit-2 JDBC Programming 46 Darshan Institute of Engineering & Technology
Step 3:Executing Statement
Once you've created a Statement object, you can then use it to
execute an SQL statement with one of its three execute methods.
ResultSet executeQuery(String sql) Returns a ResultSet object. Use this method
throws SQLException when you expect to get a result set, as you
would with a SELECT statement.
Boolean execute(String sql) Returns a boolean value of true if a ResultSet
throws SQLException object can be retrieved; otherwise, it returns
false.
int executeUpdate(String sql) Returns the number of rows affected by the
throws SQLException execution of the SQL statement.
for example, an INSERT, UPDATE, or DELETE
statement.
Unit-2 JDBC Programming 47 Darshan Institute of Engineering & Technology
Step 3: Executing Statement
Syntax:
ResultSet rs=st.executeQuery(“query”);
It holds data retrieved from a Returns a ResultSet object. Use this
database after you execute an SQL method when you expect to get a
query using Statement objects. It result set, as you would with a
acts as an iterator to allow you to SELECT statement.
move through its data.
Example
ResultSet rs = stmt.executeQuery
("SELECT * from diet");
Unit-2 JDBC Programming 48 Darshan Institute of Engineering & Technology
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * from diet");
ResultSet rs
Enr_no Name Branch
601 abc ce
602 pqr me
Database
603 rst ec
604 def Ci
Unit-2 JDBC Programming 49 Darshan Institute of Engineering & Technology
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * FROM diet WHERE
Enr_no='601'OR Enr_no='602'");
ResultSet rs
Enr_no Name Branch
Database
601 abc ce
602 pqr me
Unit-2 JDBC Programming 50 Darshan Institute of Engineering & Technology
Step 4:Processing data returned by the DBMS
Method: Resultset
boolean next() Moves the cursor forward one row from its
Throws SQLException current position.
String getString Retrieves the value of the designated column in
(int col_Index) the current row of this ResultSet object as
throws SQLException a String
String getString Retrieves the value of the designated column in
(String col_Label) the current row of this ResultSet object as
throws SQLException a String in the Java programming language.
int getInt Returns the int in the current row in the
(int columnIndex) throws specified column index.
SQLException
int getInt Retrieves the value of the designated column in
(String columnLabel) the current row
throws SQLException
Unit-2 JDBC Programming 51 Darshan Institute of Engineering & Technology
Processing data returned by the DBMS
Example
Returns the value of
while(rs.next()) specified Column number
{
System.out.println(rs.getString(1));
System.out.println(rs.getInt(“emp_id”));
}
Returns the value of specified Column name
Unit-2 JDBC Programming 52 Darshan Institute of Engineering & Technology
Step 5:Terminating Connection with DBMS
The connection of DBMS is terminated by using close() method.
Example
Releases this ResultSet object's
database and JDBC resources
rs.close(); immediately
st.close(); Releases this Statement object's
database and JDBC resources
immediately
con.close();
Releases this Connection object's
database and JDBC resources
immediately
Unit-2 JDBC Programming 53 Darshan Institute of Engineering & Technology
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLServ jdbc:microsoft:sqlserver:
erDriver //hostname:1433;DatabaseName
Unit-2 JDBC Programming 54 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 55 Darshan Institute of Engineering & Technology
JDBC Program
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu",
“root”, “pwd”);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
* from diet");
while(rs.next())
System.out.print(rs.getString(1));
stmt.close();
conn.close();
Unit-2 JDBC Programming 56 Darshan Institute of Engineering & Technology
First JDBC Program
1. import java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
Database name
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu","root",”pwd");
8. Statement stmt = conn.createStatement();
9. ResultSet rs = stmt.executeQuery("SELECT * from diet");
10. while(rs.next()){
11. System.out.print(rs.getInt(1)+"\t");
Table name
12. System.out.print(rs.getString(“Name”)+"\t");
13. System.out.println(rs.getString(3));
14. }//while
15. stmt.close();
16. conn.close();
17. }catch(Exception e){System.out.println(e.toString());
18. }//PSVM }//class
Unit-2 JDBC Programming 57 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 58 Darshan Institute of Engineering & Technology
Types of Statement
The JDBC Statement, PreparedStatement and
CallableStatement interface define the methods and
properties that enable you to send SQL or PL/SQL commands and
receive data from your database.
java.sql interface
Used for general-purpose access to your
Statement database.
Useful when
Used for static
youSQLplan
statements.
to use the SQL
Cannot accept parameters.
statements multiple times. The
PreparedStatement interface accepts
PreparedStatement input parameters at runtime.
Used when you want to access the
database stored procedures. The
CallableStatement CallableStatement interface can also
accept runtime input parameters.
Unit-2 JDBC Programming 59 Darshan Institute of Engineering & Technology
Prepared Statement
The PreparedStatement interface extends the Statement interface.
It represents a precompiled SQL statement.
A SQL statement is precompiled and stored in a Prepared
Statement object.
This object can then be used to efficiently execute this statement
multiple times.
Parameter 3
Example Parameter 1
String query="insert into student values(?,?,?)";
Table Name
Parameter 2
Unit-2 JDBC Programming 60 Darshan Institute of Engineering & Technology
Methods of PreparedStatement interface
public void Sets the integer value to the given parameter
setInt(int paramIndex, int value) index.
public void Sets the String value to the given parameter
setString(int paramIndex, String value) index.
public void Sets the float value to the given parameter
setFloat(int paramIndex, float value) index.
public void Sets the double value to the given parameter
setDouble(int paramIndex, double 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.
Unit-2 JDBC Programming 61 Darshan Institute of Engineering & Technology
Prepared Statement
Now to create table in mysql.
create table gtu.DietStudent
(
Enr_no VARCHAR(10) not null
Name VARCHAR(20),
Branch VARCHAR(10),
Division VARCHAR(10),
primary key (Enr_no)
)
Unit-2 JDBC Programming 62 Darshan Institute of Engineering & Technology
Example of PreparedStatement that inserts the record
1. import java.sql.*;
2. public class PreparedInsert {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
8. String query="insert into dietstudent values(?,?,?,?)";
9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, "14092"); //Enr_no
11. ps.setString(2, "abc_comp"); //Name
12. ps.setString(3, "computer"); //Branch
13. ps.setString(4, "cx"); //Division
14. int i=ps.executeUpdate();
15. System.out.println("no. of rows updated ="+i);
16. ps.close();
17. conn.close();
18. }catch(Exception e){System.out.println(e.toString());} }//PSVM
}//class
Unit-2 JDBC Programming 63 Darshan Institute of Engineering & Technology
Why to use PreparedStatement?
Improves performance:
The performance of the application will be faster, if you use
PreparedStatement interface because query is compiled only
once.
This is because creating a PreparedStatement object by explicitly
giving the SQL statement causes the statement to be precompiled
within the database immediately.
Thus, when the PreparedStatement is later executed, the DBMS
does not have to recompile the SQL statement.
Late binding and compilation is done by DBMS.
Provides the programmatic approach to set the values.
Unit-2 JDBC Programming 64 Darshan Institute of Engineering & Technology
GTU Exam Question
1. Show the use of PreparedStatement object to run Sum’16
precompiled SQL statement. Also write example of
java snippet for PreparedStaement.[7]
2. Explain the use of PreparedStatement with Win’16
appropriate example.[7]
3. Explain role of Prepared Statement with example.[7] Sum’17
4. Write a program to insert student records to Win’17
database using prepared statement.[7]
5. Explain the use of the PreparedStatement object of Win’18
the JDBC with an appropriate example.[7]
6. Write difference between statement and prepared Win’19
statement interface.[3]
Unit-2 JDBC Programming 65 Darshan Institute of Engineering & Technology
Callable Statement
CallableStatement interface is used to call the stored procedures.
We can have business logic on the database by the use of stored
procedures that will make the performance better as they are
precompiled.
Example
Suppose you need to get the age an employee based on the date of
birth, you may create a procedure that receives date as the input and
returns age of the employee as the output.
Unit-2 JDBC Programming 66 Darshan Institute of Engineering & Technology
Callable Statement
Three types of parameters exist: IN, OUT, and INOUT. The
PreparedStatement object only uses the IN parameter. The
CallableStatement object can use all the three.
Parameter Description
IN A parameter whose value is unknown when the SQL statement is
created. You bind values to IN parameters with the setXXX()
methods.
OUT A parameter whose value is supplied by the SQL statement it
returns. You retrieve values from the OUT parameters with the
getXXX() methods.
INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.
Unit-2 JDBC Programming 67 Darshan Institute of Engineering & Technology
Callable Statement
Create mysql procedure to get book title for given ISBN number.
Table: book
DB Column Name
DB Column Name
Unit-2 JDBC Programming 68 Darshan Institute of Engineering & Technology
Example CallableStatement
1. import java.sql.*;
2. public class CallableDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
8. CallableStatement cs=conn.prepareCall("{call gettitle(?,?)}");
9. cs.setInt(1,1201);
10. cs.registerOutParameter(2,Types.VARCHAR); Procedure Name
11. cs.execute();
12. System.out.println(cs.getString(2));
13. cs.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class
Unit-2 JDBC Programming 69 Darshan Institute of Engineering & Technology
GTU Exam Question
1. Explain role of Callable Statement with example[7] Sum’17
2. Discuss CallableStatement with example.[4] Win’17
3. What is CallableStatement? Show that how to use it Win’18
to call a stored procedure running at database layer.
[7]
Unit-2 JDBC Programming 70 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 71 Darshan Institute of Engineering & Technology
Method: ResultSet
Categories
1. Navigational methods Used to move the cursor around.
2. Get methods Used to view the data in the columns of the current row
being pointed by the cursor.
3. Update methods Used to update the data in the columns of the current
row. The updates can then be updated in the underlying
database as well.
Unit-2 JDBC Programming 72 Darshan Institute of Engineering & Technology
ResultSet: Navigational methods
boolean first() Moves the cursor to the first row.
throws SQLException
boolean last() Moves the cursor to the last row.
throws SQLException
boolean next() Moves the cursor to the next row. This method
throws SQL Exception returns false if there are no more rows in the result
set.
boolean previous() Moves the cursor to the previous row. This method
throws SQLException returns false if the previous row is off the result set.
boolean absolute(int row) throws Moves the cursor to the specified row.
SQLException
boolean relative(int row) throws Moves the cursor the given number of rows forward
SQLException or backward, from where it is currently pointing.
int getRow() Returns the row number that the cursor is pointing to.
throws SQLException
Unit-2 JDBC Programming 73 Darshan Institute of Engineering & Technology
ResultSet: Get methods
int getInt(String columnName) Returns the int in the current row in the column
throws SQLException named columnName.
int getInt(int columnIndex) throws Returns the int in the current row in the specified
SQLException column index. The column index starts at 1,
meaning the first column of a row is 1, the second
column of a row is 2, and so on.
String getString(String columnLabel) Retrieves the value of the designated column in
throws SQLException the current row of this ResultSet object as
a String in the Java programming language.
String getString(int columnIndex) Retrieves the value of the designated column in
throws SQLException the current row of this ResultSet object as
a String in the Java programming language.
Unit-2 JDBC Programming 74 Darshan Institute of Engineering & Technology
ResultSet: Update methods
void updateString(int col_Index, String s) Changes the String in the specified column to
throws SQLException the value of s.
void updateInt(int col_Index, int x) Updates the designated column with
throws SQLException an int value.
void updateFloat(int col_Index, float x) Updates the designated column with
throws SQLException a float value.
void updateDouble(int col_Index,double x) Updates the designated column with
throws SQLException a double value.
Unit-2 JDBC Programming 75 Darshan Institute of Engineering & Technology
Types of ResultSet
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the
result set.
Default
Type
ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and
backward, and the result set is not sensitive
to changes made by others to the database
that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE The cursor can scroll forward and
backward, and the result set is sensitive to
changes made by others to the database
that occur after the result set was created.
Unit-2 JDBC Programming 76 Darshan Institute of Engineering & Technology
Concurrency of ResultSet
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set.
ResultSet.CONCUR_UPDATABLE Creates an updateable result set. Default
Type
Unit-2 JDBC Programming 77 Darshan Institute of Engineering & Technology
ResultSet
try {
Statement stmt = conn.createStatement(
ResultSet Type
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) ResultSet Concurrency
{
....
}
Unit-2 JDBC Programming 78 Darshan Institute of Engineering & Technology
GTU Exam Question
1. What is ResultSet interface. Write various method for Win’19
ResultSet interface. Write a code to update record
using this interface.[7]
Unit-2 JDBC Programming 79 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 80 Darshan Institute of Engineering & Technology
ResultSetMetaData Interface
The metadata means data about data.
If you have to get metadata of a table like
i. total number of column
ii. column name
iii. column type etc.
ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.
Unit-2 JDBC Programming 81 Darshan Institute of Engineering & Technology
Method: ResultSetMetaData
int getColumnCount() it returns the total number of columns in the
throws SQLException ResultSet object.
String getColumnName(int index) it returns the column name of the specified column
throws SQLException index.
String getColumnTypeName(int it returns the column type name for the specified
index) index.
throws SQLException
Unit-2 JDBC Programming 82 Darshan Institute of Engineering & Technology
ResultSetMetaData
1. import java.sql.*;
2. public class MetadataDemo {
3. public static void main(String[] args) {
4. try {Class.forName("com.mysql.jdbc.Driver");
5. Connection conn= DriverManager.getConnection
6. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
7. Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from gtu");
9. ResultSetMetaData rsmd=rs.getMetaData();
10. System.out.println("Total columns: "+rsmd.getColumnCount());
11. System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
12. System.out.println("Column Type Name of 1st column:“
+rsmd.getColumnTypeName(1));
13. stmt.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class
Unit-2 JDBC Programming 83 Darshan Institute of Engineering & Technology
DatabaseMetadata
DatabaseMetaData interface provides methods to get meta data
of a database such as
1. database product name,
2. database product version,
3. driver name,
4. name of total number of tables etc.
Unit-2 JDBC Programming 84 Darshan Institute of Engineering & Technology
DatabaseMetadata
1. Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/temp6","root","root");
2. DatabaseMetaData dbmd=con.getMetaData();
3. System.out.println("getDatabaseProductName:“
+dbmd.getDatabaseProductName());
4. System.out.println("getDatabaseProductVersion():“
+dbmd.getDatabaseProductVersion());
5. System.out.println("getDriverName():"+dbmd.getDriverName());
6. System.out.println("getDriverVersion():“
+dbmd.getDriverVersion());
7. System.out.println("getURL():"+dbmd.getURL());
8. System.out.println("getUserName():"+dbmd.getUserName());
Unit-2 JDBC Programming 85 Darshan Institute of Engineering & Technology
GTU Exam Question
1. Explain use of DatabaseMetaData with example.[3] Sum’18
Win’18
2. Explain ResultSetMetaData with suitable program. Win’18
[3]
Unit-2 JDBC Programming 86 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 87 Darshan Institute of Engineering & Technology
Executing SQL updates
1. import java.sql.*;
2. class UpdateDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. Statement stmt=con.createStatement();
8. String query="update diet set Name='abc601' where
Enr_no=601";
9. int i=stmt.executeUpdate(query);
10. System.out.println("total no. of rows updated="+i);
11. stmt.close();
12. con.close();
13. }catch(Exception e){ System.out.println(e);}
14.} }
Unit-2 JDBC Programming 88 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 89 Darshan Institute of Engineering & Technology
Transaction Management
Transaction Succeed
mit
m
Co
Transaction
Initial State
Ro
llb
a ck
Transaction Failed
Unit-2 JDBC Programming 90 Darshan Institute of Engineering & Technology
Transaction Management
In JDBC, Connection interface provides methods to manage
transaction.
void setAutoCommit(boolean status) It is true by default, means each
transaction is committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
Unit-2 JDBC Programming 91 Darshan Institute of Engineering & Technology
Transaction Management:commit
1. import java.sql.*;
2. class CommitDemo{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/GTU","root","root");
8. con.setAutoCommit(false);//bydefault it is true
9. Statement stmt=con.createStatement();
10. int i=stmt.executeUpdate("insert into diet
values(605,'def','ci')");
11. System.out.println("no. of rows inserted="+i);
12. con.commit();//commit transaction
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15.}}
Unit-2 JDBC Programming 92 Darshan Institute of Engineering & Technology
Transaction Management:rollback
1. import java.sql.*;
2. class RollbackDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into diet
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into diet values(607,'mno','ch')");
12. System.out.println("no. of rows inserted="+i);
13. con.rollback(); //Rollback Transaction
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16.}}
Unit-2 JDBC Programming 93 Darshan Institute of Engineering & Technology
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
Unit-2 JDBC Programming 94 Darshan Institute of Engineering & Technology
Batch Processing in JDBC
Instead of executing a single query, we can execute a batch
(group) of queries.
It makes the performance fast.
The java.sql.Statement and java.sql.PreparedStatement interfaces
provide methods for batch processing.
Methods of Statement interface
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.
Unit-2 JDBC Programming 95 Darshan Institute of Engineering & Technology
Batch Processing in JDBC
1. Class.forName("com.mysql.jdbc.Driver");
2. Connection con=DriverManager.getConnection(
3. "jdbc:mysql://localhost:3306/GTU","root","root");
4. con.setAutoCommit(false);
5. Statement stmt=con.createStatement();
6. String query1,query2,query3,query4,query5; Create table
7. query1="create table DietStudent(enr INT PRIMARY KEY, name VARCHAR(20),sem
INT,branch VARCHAR(10))";
8. query2="insert into DietStudent values(6001,'java',6,'ce')"; Insert record
9. query3="insert into DietStudent values(6002,'php',6,'ce')";
10. query4="update DietStudent set name='cg' where enr=6002"; Update record
11. query5="delete from DietStudent where name='java'";
12. stmt.addBatch(query1);
13. stmt.addBatch(query2); Delete record
14. stmt.addBatch(query3);
15. stmt.addBatch(query4);
16. stmt.addBatch(query5);
17. int[] i=stmt.executeBatch();
18. con.commit();
Unit-2 JDBC Programming 96 Darshan Institute of Engineering & Technology
Transaction Isolation Level
JDBC isolation level represents that, how a database maintains its
interiority against the problem such as
1. dirty reads
2. non-repeatable reads
3. phantom reads
that occurs during concurrent transactions.
Unit-2 JDBC Programming 97 Darshan Institute of Engineering & Technology
Transaction Isolation Level
What is Phantom read?
At the time of execution of a transaction, if two queries that are
identical and executed, and the no. of rows returned are different
from other.
If you execute a query at time T1 and re-execute it at time T2,
additional rows may have been added/deleted to/from the
database, which may affect your results.
It is stated that a phantom read occurred.
Unit-2 JDBC Programming 98 Darshan Institute of Engineering & Technology
Transaction Isolation Level
What is Dirty read?
Dirty read occurs when one transaction is changing the record,
and the other transaction can read this record before the first
transaction has been committed or rolled back.
This is known as a dirty read scenario because there is always a
possibility that the first transaction may rollback the change,
resulting in the second transaction having read an invalid data.
Transaction A begins Transaction B begins
UPDATE EMPLOYEE SET SELECT * FROM EMPLOYEE;
SALARY = 10000 WHERE (Transaction B reflects data which is
EMP_ID= ‘123’; updated by transaction A. But,
those updates have not yet been
committed).
Unit-2 JDBC Programming 99 Darshan Institute of Engineering & Technology
Transaction Isolation Level
What is Non-Repeatable Read?
Non Repeatable Reads happen when in a same transaction same
query yields to a different result.
This occurs when one transaction repeatedly retrieves the data,
while a difference transactions alters the underlying data.
This causes the different or non-repeatable results to be read by
the first transaction.
Unit-2 JDBC Programming 100 Darshan Institute of Engineering & Technology
Transaction Isolation Level:program
1. public class IsolationDemo {
2. public static void main(String[] args) throws
ClassNotFoundException, SQLException {
3. Class.forName("com.mysql.jdbc.Driver");
4. Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ce17","root","diet");
5. Statement st=con.createStatement();
6. System.out.println("getTransactionIsolation="
+con.getTransactionIsolation());
7. con.setTransactionIsolation(TRANSACTION_SERIALIZABLE);
8. System.out.println("NEW getTransactionIsolation="
+con.getTransactionIsolation());
9. }
10.}
Unit-2 JDBC Programming 101 Darshan Institute of Engineering & Technology
Phantom reads vs Non-repeatable reads
Phantom Reads Non-Repeatable Reads
T Transaction Transaction T Transaction Transaction
A B A B
T1 T1
Read n=5 Read n=5
T2 T2
Read n=5 Read n=5
T3 T3
Delete n Update=8
T4 T4
Read n Read n=8
Variable
Undefined
Same query had
retrieved two
different value
Unit-2 JDBC Programming 102 Darshan Institute of Engineering & Technology
Transaction Isolation Level
Int Val. Isolation Level Description
1 TRANSACTION_READ_UNCOMMITTED It allows non-repeatable reads, dirty
reads and phantom reads to occur
2 TRANSACTION_READ_COMMITTED It ensures only those data can be read
which is committed. Prevents dirty
reads.
4 TRANSACTION_REPEATABLE_READ It is closer to serializable, but phantom
reads are also possible.
Prevents dirty and non-repeatable
reads.
8 TRANSACTION_SERIALIZABLE In this level of isolation dirty reads,
non-repeatable reads, and phantom
reads are prevented.
One can get/set the current isolation level by using methods of Connection
interface:
1. getTransactionIsolation()
2. setTransactionIsolation(int isolationlevelconstant)
Unit-2 JDBC Programming 103 Darshan Institute of Engineering & Technology
SQL Exception
java.sql.SQLException It is a core JDBC exception class that provides
information about database access errors and
other errors. Most of the JDBC methods throw
SQLException.
java.sql. It provides the update counts for all commands
BatchUpdateException that were executed successfully during the batch
update.
java.sql.DataTruncation reports a DataTruncation warning (on reads) or
throws a DataTruncation exception (on writes)
when JDBC unexpectedly truncates a data value.
java.sql.SQLWarning provides information about database access
warnings.
Unit-2 JDBC Programming 104 Darshan Institute of Engineering & Technology
GTU Questions:
1. What is JDBC? [Sum -16]
List out different types of JDBC driver and explain role of each. [Win -16]
Write code snippet for each type of JDBC connection. [Sum -18]
Explain Thick and Thin driver. [Win -18]
Comment on selection of driver. [Win -19]
2. Explain Prepared statements with suitable example [Sum -16]
[Win -16]
[Win -17]
[Win -18]
3. Give the use of Statement, PreparedStatement and CallableStatement [Win -14]
object. Write code to insert three records into student table using
PreparedStatement (assume student table with Name, RollNo, and Branch
field).
4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16]
5. Discuss CallableStatement with example. [Win -17]
[Win -18]
6. What is ResultSet interface. Write various method for ResultSet interface. [Win -19]
Write a code to update record using this interface.
Unit-2 JDBC Programming 105 Darshan Institute of Engineering & Technology
GTU Questions:
7. Explain JDBC Transaction Management in detail. [Win -19]
8. Explain use of DatabaseMetaData with example. [Sum -18]
[Win -18]
9. Explain ResultSetMetaData with suitable program. [Win -18]
10. Write a sample code to store image in Database. [Win -19]
Unit-2 JDBC Programming 106 Darshan Institute of Engineering & Technology
JDBC Interview Questions
1. What is the difference between execute, executeQuery, executeUpdate?
2. What are the benefits of PreparedStatement over Statement?
3. What is JDBC Savepoint? How to use it?
4. What is JDBC Connection isolation levels?
5. What is CLOB and BLOB datatypes in JDBC?
6. What is difference between java.util.Date and java.sql.Date?
7. What is SQL Warning? How to retrieve SQL warnings in the JDBC program?
8. Which type of JDBC driver is the fastest one?
9. What is the return type of Class.forName() method?
10. What happens if we call resultSet.getInt(0).
11. How can we set null value in JDBC PreparedStatement?
12. Prepared Statements are faster. Why?
13. What are the exceptions in JDBC?
Unit-2 JDBC Programming 107 Darshan Institute of Engineering & Technology