0% found this document useful (0 votes)
10 views77 pages

AJava GTU Study Material Presentations Unit-2 17032021071519AM

Java Material

Uploaded by

Dhruv Jaradi
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)
10 views77 pages

AJava GTU Study Material Presentations Unit-2 17032021071519AM

Java Material

Uploaded by

Dhruv Jaradi
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/ 77

Advanced java Programming

GTU #3160707

Unit-2
JDBC Programming

Computer Engineering Department


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

5 Java Server Faces 11


6 Hibernate Black Book “ Java server programming” J2EE, 1st ed., Dream 15
Tech Publishers, 2008. 3. Kathy walrath ”
7 Java Web Frameworks: Spring 21
MVC

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 2


Subject Overview
Sr.
Unit % Weightage
No.
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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 3


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 4


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 5


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.

 What is 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 6


Introduction: JDBC API
 JDBC API allows java programs to
 Make a connection with database
 Creating SQL statements
 Execute SQL statement
 Viewing & Modifying the resulting records
Java DB API DBMS Engine
Java Application
1. Create a connection
1. Open a Connection Session
2. Send a statement 2. Execute statement
3. Retrieve results 3. Send results
4. Close a connection 4. Close the session

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 7


The JDBC Connectivity Model

JDBC API

JAVA
JDBC Driver
Application Database

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 8


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 driver
database is used to access each data
JDBC Driver source.
Manager

JDBC Driver JDBC Driver JDBC Driver


Database is a
collection of
organized
information
ODBC Data
Oracle SQL Server Source

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 9


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 10


JDBC Driver: Type 1 (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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 11


JDBC Driver: Type 1 (JDBC-ODBC Driver)
Local Computer

Java Application
DB Vendor
Application Code Driver

Type 1
JDBC ODBC Bridge ODBC Driver Local
DBMS

Vendor Specific Protocol Network Communication

Database Server

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 12


JDBC Driver: Type 1 (JDBC-ODBC Driver)

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 13


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 14


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 15


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
Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 16
JDBC Driver: Type 2 (Native Code Driver)

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 17


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 18


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 19


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 20


JDBC Driver: Type 3 (Java Protocol)

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 21


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 22


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 23


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 24


JDBC Driver: Type 4 (Database Protocol)

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 25


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 26


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 27


Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Java Protocol/
Name: JDBC-ODBC Bridge Native Code Driver/ JNI Database Protocol
Middleware
Vendor
No Yes No Yes
Specific:
Pure Java
No No Yes Yes
Driver
JDBC call -> middleware
JDBC-> ODBC call JDBC call -> native
Working specific. JDBC call ->DB specific call
ODBC -> native call specific call
Middleware -> native call
Yes Yes
Multiple DB [only ODBC supported No [DB Driver should be in No
DB] middleware]

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 28


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 29


JDBC Components
The JDBC API provides the following interfaces and classes
Package java.sql
It acts as an interface between user and
Class

DriverManager
drivers. It keeps track of the drivers that
are available and handles establishing a
This interface
connection handlesathe
between communications
database and the
Driver
with the database
appropriate driver. server. Driver interface
provides vendor-specific implementations
Connection of the
This abstract
Interface classes
is the provided
session by java
between the
Interface

JDBC API. and database. It contains all


application
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
iterator to allow you to move through its
Exception

SQLException This
data.class handles any errors that occur in a
database application.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 31


JDBC Package
 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.

java.sql

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 32


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 33


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


Class.forName()
classes and interfaces in is used It is used to initiate
a forrunning
loading classJava
dynamically Driver at runtime
Sub-Pakage
application.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 34


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 database URL.
getConnection(String url) The DriverManager attempts to select an appropriate driver from the set of
throws SQLException registered JDBC drivers.
public static Connection Attempts to establish a connection to the given database URL.
getConnection(String url, url - a database url of the form jdbc:subprotocol:subname
String user, String password) user - the database user on whose behalf the connection is being made
throws SQLException password - the user's password

Interface of java.sql package


Connection conn= DriverManager.getConnection(URL,USER_NM,PASS);
Example: Class of java.sql package Database Name
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu","root", "pwd");
Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 35
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-purpose Statement createStatement()


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 36


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 when you expect to get a result set, as
throws SQLException you would with a SELECT statement.
Boolean execute(String sql) Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it
throws SQLException returns false.
int executeUpdate(String sql) Returns the number of rows affected by the execution of the SQL statement.
throws SQLException for example, an INSERT, UPDATE, or DELETE statement.

Syntax:
ResultSet rs=st.executeQuery(“query”);
It holds data retrieved from a
database after you execute an Returns a ResultSet object. Use this
SQL query using Statement method when you expect to get a
objects. It acts as an iterator to result set, as you would with a
allow you to move through its SELECT statement.
data.
Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 37
Step 3: Executing Statement
Example :
ResultSet rs = stmt.executeQuery("SELECT * from diet");

Database

ResultSet rs
Enr_no Name Branch
601 abc ce
602 pqr me
603 rst ec
604 def Ci

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 38


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 39


Step 4:Processing data returned by the DBMS
 Method: Resultset
boolean next() Moves the cursor forward one row from its current position.
Throws SQLException
String getString (int col_Index) Retrieves the value of the designated column in the current row of
throws SQLException this ResultSet object as a String
String getString Retrieves the value of the designated column in the current row of
(String col_Label) this ResultSet object as a String in the Java programming language.
throws SQLException
int getInt(int columnIndex) throws Returns the int in the current row in the specified column index.
SQLException
int getInt(String columnLabel) Retrieves the value of the designated column in the current row
throws SQLException

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 40


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
 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
Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 41
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.SQLServerDriver jdbc:microsoft:sqlserver:
//hostname:1433;DatabaseName

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 42


JDBC Program
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection("jdbc:mysql://l
ocalhost: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();

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 43


First JDBC Program
ConnDemo.java
1 import java.sql.*;
2 public class ConnDemo {
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 Statement stmt = conn.createStatement();
9 ResultSet rs = stmt.executeQuery("SELECT * from diet");
10 while(rs.next()){
11 System.out.print(rs.getInt(1)+"\t");
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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 44


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
youSQL statements.
plan to use the SQL
Cannot accept parameters.
statements multiple times. The
PreparedStatement interface accepts input
PreparedStatement parameters at runtime.
Used when you want to access the
database stored procedures. The
CallableStatement CallableStatement interface can also
accept runtime input parameters.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 45


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 46


Methods of PreparedStatement interface
public void setInt(int paramIndex, int value) Sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) Sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) Sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) Sets the double value to the given parameter 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 47


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 48


Example of PreparedStatement that inserts the record
PreparedInsert.java
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",
8 "root",“pwd");
9 String query="insert into dietstudent values(?,?,?,?)";
10
11 PreparedStatement ps=conn.prepareStatement(query);
12 ps.setString(1, "14092"); //Enr_no
13 ps.setString(2, "abc_comp"); //Name
14 ps.setString(3, "computer"); //Branch
15 ps.setString(4, "cx"); //Division
16 int i=ps.executeUpdate();
17 System.out.println("no. of rows updated ="+i);
18
19 ps.close();
20 conn.close();
21 }catch(Exception e){System.out.println(e.toString());} }//PSVM
22 }//class
Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 49
Why to use PreparedStatement?
 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 50


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 51


Callable Statement
 Create mysql procedure to get book title for given ISBN number.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 52


Example CallableStatement
CallableDemo.java
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",
8 "root",“pwd");
9
10 CallableStatement cs=conn.prepareCall("{call gettitle(?,?)}");
11 cs.setInt(1,1201);
12 cs.registerOutParameter(2,Types.VARCHAR);
Procedure Name
13 cs.execute();
14 System.out.println(cs.getString(2));
15
16 cs.close();
17 conn.close();
18 }catch(Exception e){System.out.println(e.toString());}
19 }//PSVM
20 }//class

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 53


Method: ResultSet
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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 54


ResultSet: Navigational methods
boolean first() throws SQLException Moves the cursor to the first row.
boolean last() throws SQLException Moves the cursor to the last row.
boolean next() throws SQL Exception Moves the cursor to the next row. This method returns false if there are no
more rows in the result set.

boolean previous() Moves the cursor to the previous row. This method returns false if the
throws SQLException previous row is off the result set.
boolean absolute(int row) throws SQLException Moves the cursor to the specified row.

boolean relative(int row) throws SQLException Moves the cursor the given number of rows forward or backward, from
where it is currently pointing.
int getRow() throws SQLException Returns the row number that the cursor is pointing to.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 55


ResultSet: Get methods

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

int getInt(int columnIndex) throws SQLException Returns the int in the current row in the specified 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 the current row of
throws SQLException this ResultSet object as a String in the Java programming language.

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 56


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

void updateInt(int col_Index, int x) throws SQLException Updates the designated column with an int value.
void updateFloat(int col_Index, float x) throws SQLException Updates the designated column with a float value.
void updateDouble(int col_Index,double x) Updates the designated column with a double value.
throws SQLException

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 57


Types of ResultSet
Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.

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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 58


Concurrency of ResultSet
Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set.

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 59


How to set Type and Concurrency ?
 createStatement(int RSType, int RSConcurrency);

 prepareStatement(String SQL, int RSType, int RSConcurrency);

 prepareCall(String sql, int RSType, int RSConcurrency);

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 60


ResultSetMetaData Interface
 The metadata means data about data.
 If you have to get metadata of a table like
 total number of column
 column name
 column type etc.
 ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 61


Method: ResultSetMetaData
int getColumnCount() throws SQLException it returns the total number of columns in the ResultSet object.

String getColumnName(int index) throws SQLException it returns the column name of the specified column index.

String getColumnTypeName(int index) throws SQLException it returns the column type name for the specified index.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 62


ResultSetMetaData
MetadataDemo.java
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
8 (ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
9 ResultSet rs = stmt.executeQuery("SELECT * from gtu");
10
11 ResultSetMetaData rsmd=rs.getMetaData();
12 System.out.println("Total columns: "+rsmd.getColumnCount());
13 System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
14 System.out.println("Column Type Name of 1st column:“+rsmd.getColumnTypeName(1));
15
16 stmt.close();
17 conn.close();
18 }catch(Exception e){System.out.println(e.toString());}
19 }//PSVM
20 }//class

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 63


DatabaseMetadata
 DatabaseMetaData interface provides methods to get meta data of a database such as
 database product name,
 database product version,
 driver name,
 name of total number of tables etc.

DabaseInfo.java
1 Class.forName("com.mysql.jdbc.Driver");
2 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
3 "root","");
4 DatabaseMetaData dbmd=con.getMetaData();
5 System.out.println("getTransactionIsolation="+con.getTransactionIsolation());
6 System.out.println("getDatabaseProductName:" +dbmd.getDatabaseProductName());
7 System.out.println("getDatabaseProductVersion():"+dbmd.getDatabaseProductVersion());
8 System.out.println("getDriverName():"+dbmd.getDriverName());
9 System.out.println("getDriverVersion():"+dbmd.getDriverVersion());
10 System.out.println("getURL():"+dbmd.getURL());
11 System.out.println("getUserName():"+dbmd.getUserName());

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 64


Executing SQL updates
UpdateDemo.java
1 import java.sql.*;
2 class UpdateDemo{
3 public static void main(String args[])
4 {
5 try
6 {
7 Class.forName("com.mysql.jdbc.Driver");
8 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/GTU",
9 "root","root");
10 Statement stmt=con.createStatement();
11 String query="update diet set Name='abc601' where Enr_no=601";
12 int i=stmt.executeUpdate(query);
13 System.out.println("total no. of rows updated="+i);
14 stmt.close();
15 con.close();
16 }
17 catch(Exception e)
18 {
19 System.out.println(e);
20 }
21 } }

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 65


Transaction Management

Transaction Succeed

Transaction
Initial State

Transaction Failed

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 66


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 67


Transaction Management:commit
CommitDemo.java
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("jdbc:mysql://localhost:3306/GTU",
7 "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 }}

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 68


Transaction Management:rollback
RollbackDemo.java
1 import java.sql.*;
2 class RollbackDemo{
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);//bydeafault it is true
9 Statement stmt=con.createStatement();
10 int i=stmt.executeUpdate("insert into diet values(606,'ghi','ee')");
11 con.commit(); //Commit Transaction
12 i+=stmt.executeUpdate("insert into diet values(607,'mno','ch')");
13 System.out.println("no. of rows inserted="+i);
14 con.rollback(); //Rollback Transaction
15 con.close();
16 }catch(Exception e){ System.out.println(e);}
17 }}

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 69


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 70


Batch Processing in JDBC
Batch.java
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 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();

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 71


Transaction Isolation Level
 JDBC isolation level represents that, how a database maintains its interiority against the
problem such as
 dirty reads
 non-repeatable reads
 phantom reads
that occurs during concurrent transactions.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 72


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.

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 73


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 74


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 75


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)

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 76


Transaction Isolation Level:program
IsolationDemo.java
1 public class IsolationDemo {
2
3 public static void main(String[] args) throws ClassNotFoundException, SQLException
4 {
5 Class.forName("com.mysql.jdbc.Driver");
6 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ce17",
7 "root", "diet");
8 System.out.println("getTransactionIsolation=" + con.getTransactionIsolation());
9 con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
10 System.out.println("NEW getTransactionIsolation=" +
11 con.getTransactionIsolation());
12
13 }
14 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 77


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 were executed successfully
BatchUpdateException 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 2 – JDBC Programming 78

You might also like