0% found this document useful (0 votes)
109 views

Unit 2 JDBC Programming 28012018 040330AM

This document discusses JDBC drivers and their types. There are four main types of JDBC drivers: 1. Type 1 (JDBC-ODBC) drivers translate JDBC calls to ODBC and are not portable. They are obsolete. 2. Type 2 (Native Code) drivers translate JDBC calls to native database APIs but require client libraries. 3. Type 3 (Java Protocol) drivers translate JDBC to middleware protocols and support multiple databases but are slower. 4. Type 4 (Database Protocol) drivers communicate directly with databases using database-specific protocols. They are portable but database-specific. Thick drivers require client libraries while thin

Uploaded by

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

Unit 2 JDBC Programming 28012018 040330AM

This document discusses JDBC drivers and their types. There are four main types of JDBC drivers: 1. Type 1 (JDBC-ODBC) drivers translate JDBC calls to ODBC and are not portable. They are obsolete. 2. Type 2 (Native Code) drivers translate JDBC calls to native database APIs but require client libraries. 3. Type 3 (Java Protocol) drivers translate JDBC to middleware protocols and support multiple databases but are slower. 4. Type 4 (Database Protocol) drivers communicate directly with databases using database-specific protocols. They are portable but database-specific. Thick drivers require client libraries while thin

Uploaded by

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

Unit 2 – JDBC Programming

Q1. What is JDBC? Explain the types of JDBC drivers?


Ans. What is JDBC?
 JDBC is an API, which is used in java programming for interacting with database.
 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.

JDBC Drivers
1. Type1 (JDBC-ODBC Driver)
 Depends on support for ODBC
 Type1 is not portable driver
 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) onwards.
E.g. MS Access

Figure: Type1 (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

Swati Sharma, CE Department | 2160707 – Advanced Java 9


Unit 2 – JDBC Programming
 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.

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

Figure: 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 hence type 2 drivers
cannot be used for the Internet.
 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).
 Mostly obsolete now
 Usually not thread safe

Swati Sharma, CE Department | 2160707 – Advanced Java 10


Unit 2 – JDBC Programming
3. Type 3 (Java Protocol)
 This driver translate the jdbc calls into a database server independent and middleware
server specific calls.
 With the help of the middleware server, the translated jdbc calls further translated into
database server specific calls.
 This type of driver also known as net-protocol fully java technology-enabled driver.
 Type-3 driver is recommended to be used with applets. its auto-downloadable.
 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, and forwarded to the database server.
 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.

Figure: 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

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.

Swati Sharma, CE Department | 2160707 – Advanced Java 11


Unit 2 – JDBC Programming
4. 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
 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.
 This type of driver is lightweight and generally known as thin driver.
 You can use this driver when you want an auto downloadable option the client side
application
 i.e. thin driver for oracle from oracle corporation, weblogic and ms sqlserver4 for ms sql
server from BEA system

Figure: 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.

Swati Sharma, CE Department | 2160707 – Advanced Java 12


Unit 2 – JDBC Programming
Comparison between JDBC Drivers
Type Type 1 Type 2 Type 3 Type 4
Name JDBC-ODBC Bridge Native Code Java Protocol/ Database
Driver/ JNI Middleware Protocol
Vendor Specific No Yes No Yes
Portable No No Yes Yes
Pure Java Driver No No Yes Yes
Working JDBC-> ODBC call JDBC call -> JDBC call -> JDBC call ->DB
ODBC -> native native specific middleware specific call
call call specific.
Middleware ->
native call
Multiple DB Yes NO Yes No
[only ODBC [DB Driver should
supported DB] be in middleware]
Example MS Access Oracle OCI driver IDA Server MySQL
Execution Speed Slowest among all Faster Compared Slower Compared Fastest among
to Type1 to Type2 all
Driver Thick Driver Thick Driver Thin Driver Thin Driver

Swati Sharma, CE Department | 2160707 – Advanced Java 13


Unit 2 – JDBC Programming

Q2. Explain Thick and Thin driver. Comment on selection of driver. Write code
snippet for each type of JDBC connection.
Ans. Thick driver
 Thick client would need the client installation.
E.g. Type 1 and Type 2.

Thin driver
 The thin client driver, which mean you can connect to a database without the client installed on your
machine.
E.g. Type 4

Comment on selection of driver


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

Write code snippet for each type of JDBC connection


1. MySQL
Class.forName("com.mysql.jdbc.Driver");

Connection conn=
DriverManager.getConnection("jdbc:mysql://localhost:PortNo/database
Name",“uid”, “pwd”);

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

Connection conn=
DriverManager.getConnection("jdbc:oracle:thin:@hostname:port
Number:databaseName","root", "pwd");

3. DB2
Class.forName("com.ibm.db2.jdbc.net.DB2Driver");

Connection conn=
DriverManager.getConnection("jdbc:db2:hostname:port Number
/databaseName")

Swati Sharma, CE Department | 2160707 – Advanced Java 14


Unit 2 – JDBC Programming

Q3. Explain Statement Interface with appropriate example.


Ans. Java.sql.Statement
 Used for general-purpose access to your database.
 Useful for static SQL statements, e.g. SELECT specific row from table etc.
 The Statement interface defines a standard abstraction to execute the SQL statements requested by a
user and return the results by using the ResultSet object.
 The Statement interface is created after the connection to the specified database is made.
 The object is created using the createStatement() method of the Connection interface, as shown in
following code snippet:
Statement stmt = con.createStatement();

1. java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
4. try {
5. // Load and register the driver
6. Class.forName("com.mysql.jdbc.Driver");

7. // Establish the connection to the database server


8. Connection conn= DriverManager.getConnection
9. ("jdbc:mysql://localhost:3306/database_name","root","pwd");
10. // Create a statement
11. Statement stmt = conn.createStatement();
12. // Execute the statement
13. ResultSet rs = stmt.executeQuery("SELECT * from Table");

14. // Retrieve the results


15. while(rs.next()){
16. System.out.print(rs.getInt(1)+"\t");
17. System.out.print(rs.getString(“Name”)+"\t");
18. System.out.println(rs.getString(3));
19. }//while

20. // Close the statement and connection


21. stmt.close();
22. conn.close();
23. }catch(Exception e){System.out.println(e.toString());
24. }//PSVM
25. }//class

Swati Sharma, CE Department | 2160707 – Advanced Java 15


Unit 2 – JDBC Programming

Q4. Explain Prepared Statement with example.


Ans.  The PreparedStatement interface is subclass of the Statement interface, can be used to
represent a precompiled query, which can be executed multiple times.
 Prepared Statement is used when you plan to execute same SQL statements many times.
 PreparedStatement interface accepts input parameters at runtime.
 A SQL statement is precompiled and stored in a PreparedStatement object.
 This object can then be used to efficiently execute this statement multiple times.
 The object is created using the prepareStatement() method of Connection interface, as
shown in following snippet:

String query = “insert into emp values(? ,?)”;


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1,5);
ps.setString(2,”New Employee”);
int n = ps.executeUpdate();

Advantages:
 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.

Disadvantage:
The main disadvantage of PreparedStatement is that it can represent only one SQL statement at a
time.

Example of PreparedStatement
Write a program to insert student records to database using prepared statement
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/DIET", "root","pwd");

8. String query="insert into dietstudent values(?,?,?,?)";


9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, "14092"); //Enr_no

Swati Sharma, CE Department | 2160707 – Advanced Java 16


Unit 2 – JDBC Programming
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

Q5. Explain Callable Statement with example.


Ans.  CallableStatement interface is used to call the stored procedures.
 Therefore, the stored procedure can be called by using an object of the CallableStatement
interface.
 The object is created using the prepareCall() method of Connection interface.

CallableStatement cs=conn.prepareCall("{call Proc_Name(?,?)}");


cs.setInt(1,2222);
cs.registerOutParameter(2,Types.VARCHAR);
cs.execute();
 Three types of parameters exist: IN, OUT, and INOUT.
 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.

Swati Sharma, CE Department | 2160707 – Advanced Java 17


Unit 2 – JDBC Programming
Example of CallableStatement
Writa a Callable Statement program to retrieve branch of the student using {getBranch()
procedure} from given enrollment number. Also write code for Stored Procedure
Stored Procedure: getbranch()
1. DELIMITER @@
2. DROP PROCEDURE getbranch @@
3. CREATE PROCEDURE databaseName.getbranch
4. (IN enr_no INT, OUT my_branch VARCHAR(10))
5. BEGIN
6. SELECT branch INTO my_branch
7. FROM dietStudent
8. WHERE enr_no=enrno;
9. END @@
10. DELIMITER ;

Callable Statement program


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/Diet", "root","pwd");
8.
9. CallableStatement cs=conn.prepareCall("{call getbranch(?,?)}");
10. cs.setInt(1,2222);
11. cs.registerOutParameter(2,Types.VARCHAR);
12. cs.execute();
13. System.out.println("branch="+cs.getString(2));
14. cs.close();
15. conn.close();
16. }catch(Exceptione){System.out.println(e.toString());}
17. }//PSVM
18. }//class

Swati Sharma, CE Department | 2160707 – Advanced Java 18


Unit 2 – JDBC Programming

Q6. Differentiate Statement, Prepared Statement and Callable Statement.

Ans. Statement Prepared Statement Callable Statement


Super interface for Prepared extends Statement extends PreparedStatement
and Callable Statement (sub-interface) (sub-interface)
Used for executing simple Used for executing dynamic and Used for executing stored
SQL statements like CRUD pre-compiled SQL statements procedures
(create, retrieve, update and
delete
The Statement interface The PreparedStatement The CallableStatement interface
cannot accept parameters. interface accepts input can also accept runtime input
parameters at runtime. parameters.
stmt = PreparedStatement CallableStatement
conn.createStatement(); ps=con.prepareStatement cs=conn.prepareCall("{call
("insert into studentDiet getbranch(?,?)}");
values(?,?,?)");
java.sql.Statement is slower PreparedStatement is faster None
as compared to Prepared because it is used for
Statement in java JDBC. executing precompiled SQL
statement in java JDBC.
java.sql.Statement is suitable java.sql.PreparedStatement java.sql.CallableStatement is
for executing DDL commands is suitable for executing DML suitable for executing stored
- CREATE, drop, alter and commands - SELECT, INSERT, procedure.
truncate in java JDBC. UPDATE and DELETE in java
JDBC.

Q7. Explain JDBC Architecture.


Ans. JDBC API
 The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
 JDBC API provides classes and interfaces to connect or communicate Java application with
database.
 The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
1. JDBC API: This provides the application-to-JDBC Manager connection.
2. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

JDBC Driver Manager (Class)


 This class manages a list of database drivers.
 It 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.
Swati Sharma, CE Department | 2160707 – Advanced Java 19
Unit 2 – JDBC Programming
 Matches connection requests from the java application with the proper database driver
using communication sub protocol.
 The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database Connection.

Figure: JDBC Architecture


Driver (Interface)
 This interface handles the communications with the database server.
 You will interact directly with Driver objects very rarely.
 Instead, you use DriverManager objects, which manages objects of this type.
 It also abstracts the details associated with working with Driver objects.
Connection (Interface)
 This 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 (Interface)
 You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
ResultSet (Interface)
 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.
SQLException (Class)
This class handles any errors that occur in a database application.

Swati Sharma, CE Department | 2160707 – Advanced Java 20


Unit 2 – JDBC Programming

Q8. Explain methods of ResultSet Interface.


Ans. Categories
1. Navigational Used to move the cursor around.
methods
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.

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 returns
throws SQL Exception false if there are no more rows in the result set.
boolean previous() Moves the cursor to the previous row. This method returns
throws SQLException false if the previous row is off the result set.
boolean absolute(int row) Moves the cursor to the specified row.
throws SQLException
boolean relative(int row) Moves the cursor the given number of rows forward or
throws SQLException backward, from where it is currently pointing.
int getRow() Returns the row number that the cursor is pointing to.
throws SQLException

ResultSet: Get methods


int getInt Returns the integer value to the current row in the column
(String columnName) named columnName.
throws SQLException

int getInt Returns the integer value to the current row in the specified
(int columnIndex) column index. The column index starts at 1, meaning the
throws SQLException first column of a row is 1, the second column of a row is 2,
and so on.

Swati Sharma, CE Department | 2160707 – Advanced Java 21


Unit 2 – JDBC Programming

String getString Retrieves the value of the designated column in the current
(String columnLabel) row of this ResultSet object as a String in the Java
throws SQLException programming language.

String getString Retrieves the value of the designated column in the current
(int columnIndex) row of this ResultSet object as a String in the Java
throws SQLException programming language.

ResultSet: Update methods


void updateString Changes the String in the specified column to the value of s.
(int col_Index, String s)
throws SQLException

void updateInt Updates the designated column with an integer value.


(int col_Index, int x)
throws SQLException

void updateFloat Updates the designated column with a float value.


(int col_Index, float x)
throws SQLException

void updateDouble Updates the designated column with a double value.


(int col_Index,double x)
throws SQLException

Swati Sharma, CE Department | 2160707 – Advanced Java 22


Unit 2 – JDBC Programming

Q9. Differentiate executeQuery(), executeUpdate() and execute() with


appropriate example.

Ans. executeQuery() executeUpdate() execute()


ResultSet executeQuery int executeUpdate(String sql) Boolean execute(String sql)
(String sql) throws SQLException throws SQLException
throws SQLException
This is used generally for This is generally used for If you dont know which
reading the content of the altering the databases. method to be used for
database. The output will be Generally DROP, INSERT, executing SQL statements,
in the form of ResultSet. UPDATE, DELETE statements this method can be used. This
Generally SELECT statement will be used in this. The will return a boolean. TRUE
is used. output will be in the form of indicates the result is a
int. This int value denotes the ResultSet and FALSE indicates
number of rows affected by it has the int value which
the query. denotes number of rows
affected by the query.
E.g.:ResultSet rs= E.g.: int i= E.g.: Boolean b=
stmt.executeQuery(query); stmt.executeUpdate(query); stmt.execute(query);

Q10. Explain Resultset Type and Concurrency


Ans. Resultset Type
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.

Concurrency of ResultSet
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. (Default Type)
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

Swati Sharma, CE Department | 2160707 – Advanced Java 23


Unit 2 – JDBC Programming

Example
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);

Q11. Explain ResultsetMetaData Interface with Example.


Ans.  Metadata means data about data.
 If you have to get metadata of a table like
1. total number of column
2. column name
3. column type etc.
 ResultSetMetaData interface is useful because it provides methods to get metadata from
the ResultSet object.

Example: 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)
16. {System.out.println(e.toString());}
17. }//PSVM
18. }//class
OUTPUT:
Total columns: 3
Column Name of 1st column:Enr_no
Column Type Name of 1st column:INT

Swati Sharma, CE Department | 2160707 – Advanced Java 24


Unit 2 – JDBC Programming

Q12. Explain DatabaseMetaData Interface with Example


Ans. 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.
Example: DatabaseMetaData
import java.sql.*;
public class DatabaseMetaDataDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/temp6","r
oot","root");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println
("getDatabaseProductName:"+dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():
"+dbmd.getDatabaseProductVersion());

System.out.println("getDriverName():"+dbmd.getDriverName())
;
System.out.println("getDriverVersion():
"+dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());

} catch (Exception ex) {


System.out.println("Exception:"+ex.toString());
}}}
OUTPUT:
getDatabaseProductName:MySQL
getDatabaseProductVersion():5.6.16
getDriverName():MySQL-AB JDBC Driver
getDriverVersion():mysql-connector-java-5.1.23 ( Revision:
${bzr.revision-id} )
getURL():jdbc:mysql://localhost:3306/temp6
getUserName():root@localhost

Swati Sharma, CE Department | 2160707 – Advanced Java 25


Unit 2 – JDBC Programming

Q13. Explain Transaction Management in JDBC with appropriate example.


Ans.  Transaction Management in java is required when we are dealing with relational databases.
 By default when we create a database connection, it runs in auto-commit mode.
 It means that whenever we execute a query and it’s completed, the commit is fired
automatically.
 So every SQL query we fire is a transaction and if we are running some DML or DDL queries,
the changes are getting saved into database after every SQL statement finishes.
 Sometimes we want a group of SQL queries to be part of a transaction so that we can commit
them when all the queries runs fine. If we get any exception, we have a choice of rollback
all the queries executed as part of the transaction.

Figure: Transaction Management

Advantage of Transaction Management


 Fast performance: It makes the performance fast because database is hit at the time of
commit.

In JDBC, Connection interface provides methods to manage transaction.


void setAutoCommit(boolean status) It is true by default means each transaction is
committed by default.
void commit() Commits the transaction.
void rollback() Cancels the transaction.

Swati Sharma, CE Department | 2160707 – Advanced Java 26


Unit 2 – JDBC Programming
Example
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. }}

Q14. Explain Transaction Isolation Level in JDBC


Ans.  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.

What is Phantom read?


 At the time of execution of a transaction, if two queries that are identical are executed, and
the rows returned are different from one another.
 If you execute a query at time T1 and re-execute it at time T2, additional rows may have
been added to the database, which may affect your results. It is stated that a phantom read
occurred.

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 the possibility that the first
transaction may rollback the change, resulting in the second transaction having read an
invalid data.

Swati Sharma, CE Department | 2160707 – Advanced Java 27


Unit 2 – JDBC Programming
E.g.
Transaction A begins Transaction B begins
UPDATE EMPLOYEE SET SALARY = 10000 SELECT * FROM EMPLOYEE;
WHERE EMP_ID= ‘123’; (Transaction B sees data which is updated by
transaction A. But, those updates have not
yet been committed.)

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.

Transaction Isolation Level


Initial 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.
4 TRANSACTION_REPEATABLE_READ It is closer to serializable, but
phantom reads are also possible.
8 TRANSACTION_SERIALIZABLE In this level of isolation dirty reads,
non-repeatable reads, and
phantom reads are prevented.

You can get/set the current isolation level by using method


1. getTransactionIsolation()
2. setTransactionIsolation(int isolationlevelconstant)

Example
con.setTransactionIsolation(8);
System.out.println("con.getTransactionIsolation():"
+con.getTransactionIsolation());

Swati Sharma, CE Department | 2160707 – Advanced Java 28


Unit 2 – JDBC Programming

Q15. Explain Batch Processing in JDBC


Ans.  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.

1.Class.forName("com.mysql.jdbc.Driver");
2.Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/GTU","root","root");
3.con.setAutoCommit(false);
4.Statement stmt=con.createStatement();
5.String query1,query2,query3,query4,query5;
6.query1="create table DietStudent(enr INT PRIMARY
KEY, name VARCHAR(20),sem INT,branch
VARCHAR(10))";
7.query2="insert into DietStudent
values(6001,'java',6,'ce')";
8.query3="insert into DietStudent
values(6002,'php',6,'ce')";
9.query4="update DietStudent set name='cg' where
enr=6002";
10. query5="delete from DietStudent where
name='java'";
11. stmt.addBatch(query1);
12. stmt.addBatch(query2);
13. stmt.addBatch(query3);
14. stmt.addBatch(query4);
15. stmt.addBatch(query5);
16. int[] i=stmt.executeBatch();
17. con.commit();

Swati Sharma, CE Department | 2160707 – Advanced Java 29


Unit 2 – JDBC Programming
GTU Questions
1. What is JDBC? [Win -14]
List out different types of JDBC driver and explain role of each. [Sum -15]
Write code snippet for each type of JDBC connection. [Win -15]
Explain Thick and Thin driver. [Sum -16]
Comment on selection of driver. [Win -16]

2. Explain Prepared statements with suitable example [Win -15]


[Sum -16]
[Win -16]
[Win -17]

3. Give the use of Statement, PreparedStatement and CallableStatement object. [Win -14]
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]

Swati Sharma, CE Department | 2160707 – Advanced Java 30

You might also like