0% found this document useful (0 votes)
45 views108 pages

AJ - Unit-2 - JDBC Programming

Uploaded by

a.le.xd.ama.y.ok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views108 pages

AJ - Unit-2 - JDBC Programming

Uploaded by

a.le.xd.ama.y.ok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 108

3160707

Advanced Java Programming

Unit-2
JDBC
Programming
Reference Books
Sr. Unit Reference Book Chapter
No.
1 Java Networking The Complete Reference, Java (Seventh 20
Edition), Herbert Schild - Osbrone.
2 JDBC Programming Complete Reference J2EE by James Keogh 6,7
mcgraw publication
3 Servlet API and 7,8
Overview Professional Java Server Programming by
4 Java Server Pages Subrahmanyam Allamaraju, Cedric Buest 10,11
Wiley Publication

5 Java Server Faces 11


6 Hibernate Black Book “ Java server programming” J2EE, 15
1st ed., Dream Tech Publishers, 2008. 3.
7 Java Web Kathy walrath ” 21
Frameworks: Spring
MVC
2
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

4
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

5
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

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

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

8
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

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

10
Introduction: JDBC API
• JDBC API allows java programs to
i. Make a connection with database
ii. Creating SQL statements
iii. Execute SQL statement
Java Application

iv. Viewing & Modifying the resulting records


Java DB API
1. Open a Connection
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

11
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

12
The JDBC Connectivity Model
JDBC API

JAVA
JDBC Driver
Application Database

13
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

14
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
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

16
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".

17
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

18
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
19
20
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.

21
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
22
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
23
24
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).

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

26
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
27
28
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

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

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

31
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
32
33
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.

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

35
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]
36
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

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

38
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.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName

39
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

40
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

41
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
This and handles
interface establishingthe
handles a
Driver connection between
communications a database
with and the
the database
appropriate
server. Driverdriver. interface provides
vendor-specific implementations of the
Interface

Connection This Interface


abstract is the
classes session by
provided between java
the JDBC
application
API. and database. It 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.
42
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

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

44
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

45
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

46
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 Sub-Pakage


represent classes Main Pakage
and interfaces in Class.forName() It is used to initiate
a running Java is used for loading Driver at runtime
application. class dynamically 47
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
throws SQLException connection is being made
password - the user's password
48
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

49
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 Statement createStatement()


general-purpose access to your throws SQLException
database, when using static SQL Creates a Statement object for sending
statements at runtime. SQL statements to the database.

50
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 Returns a ResultSet object. Use this method
sql) 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.

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

52
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * from student");
ResultSet rs
Enr_no Name Branch
601 abc ce
602 pqr me
Database
603 rst ec
604 def Ci

53
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * FROM student WHERE
Enr_no='601'OR Enr_no='602'");

ResultSet rs
Enr_no Name Branch
Database
601 abc ce
602 pqr me

54
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

55
Processing data returned by the DBMS
• Example
while(rs.next()) Returns the value of
specified Column number
{
System.out.println(rs.getString(1));

System.out.println(rs.getInt(“emp_id”)
);
} Returns the value of specified Column name

56
Step 5:Terminating Connection with DBMS
• The connection of DBMS is terminated by using
close() method.
Example
Releases this ResultSet object's
rs.close(); database and JDBC resources
immediately

st.close();
Releases this Statement object's
database and JDBC resources
con.close(); immediately

Releases this Connection object's


database and JDBC resources
immediately

57
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.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName

58
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

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

while(rs.next())
System.out.print(rs.getString(1));

stmt.close();

conn.close();
60
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 student");
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

61
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

62
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
Use the for general-purpose access to
your database.
Useful for static SQL statements.
Statement Cannot accept parameters.

Use the when you plan to use the SQL


statements multiple times. The
PreparedStatement PreparedStatement interface accepts
input parameters at runtime.
Use the when you want to access the
database stored procedures. The
CallableStatement CallableStatement interface can also
accept runtime input parameters. 63
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
64
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.

65
Prepared Statement
• Now to create table in mysql.
create table gtu.student2
(
Enr_no VARCHAR(10) not null
Name VARCHAR(20),
Branch VARCHAR(10),
Division VARCHAR(10),
primary key (Enr_no)
)

66
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 student2 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

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

68
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]

69
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 the 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.
70
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.
71
Callable Statement
• Create mysql procedure to get book title for given
ISBN number.
Table: book

DB Column Name

DB Column Name

72
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
11. cs.execute(); Name
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

73
GTU Exam Question
1. Explain role of Callable Statement with example[7] Sum’17
2. Discuss CallableStatement with example.[4] Win’17

74
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

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

76
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

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

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

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

80
Concurrency of ResultSet
Concurrency Description
ResultSet.CONCUR_READ_ONL Creates a read-only result set. Default
Type
Y
ResultSet.CONCUR_UPDATABL Creates an updateable result set.
E

81
ResultSet
try {
Statement stmt =
conn.createStatement( ResultSet Type
ResultSet.TYPE_FORWARD_ONLY,

ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
.... ResultSet Concurrency

82
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

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

84
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

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

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

87
DatabaseMetadata
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/temp6","root","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());

88
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

89
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 student 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. } }

90
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

91
Transaction Management
Transaction Succeed

it
m m
Co

Transaction
Initial State
Ro
llba
ck

Transaction Failed

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

93
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 student
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. }}

94
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 student
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into student 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. }}

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

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

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

98
Transaction Isolation Level
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 other.
• 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.

99
Phantom reads vs Non-repeatable reads

Phantom Reads Non-Repeatable Reads


T Transaction Transaction T Transaction Transaction
A B A B
T1 Read n=5 T1 Read n=5
T2 Read n=5 T2 Read n=5
T3 Delete n T3 Update=8
T4 Read n T4 Read n=8

Variable
Undefined
Same query had
retrieved two
different value

100
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 method:


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

101
Transaction Isolation Level:program
IsolationDemo.java
public class IsolationDemo {
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306 /ce17","root",
“rngpit");

System.out.println("getTransactionIsolation=" +
con.getTransactionIsolation());

con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

System.out.println("NEW getTransactionIsolation=" +
con.getTransactionIsolation());
}
}

102
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 that
BatchUpdateException 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.

103
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

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

105
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();
Create table
6. String query1,query2,query3,query4,query5;
7. query1="create table student(enr INT PRIMARY KEY, name VARCHAR(20),sem
INT,branch VARCHAR(10))";
8. query2="insert into student values(6001,'java',6,'ce')"; Insert
record
9. query3="insert into student values(6002,'php',6,'ce')";
10. query4="update student set name='cg' where enr=6002";
Update record
11. query5="delete from student 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();

106
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 [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]

107
JDBC Interview Question
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 does Class.forName return?
10. What happens if we call resultSet.getInt(0).

108

You might also like