Unit - 1
Unit - 1
Unit - 1
Prepaid by
Prof. P .V. Parmar
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
2
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.
Example
Oracle
MS Access
My SQL
SQL Server
..
.
3
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.
4
What is an API?
• Application Program Interface
• A set of routines, protocols, and tools for
building software applications.
5
Introduction: JDBC API
• JDBC API allows java programs to
i. Making a connection to a 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
6
The JDBC Connectivity Model
JDBC API
JAVA
JDBC Driver
Application Database
7
JDBC Architecture
A Java program that runs stand
It provides classes & interfaces alone in a client or server.
to connect or communicate
Java application with database.
This class manages a list of
database drivers.
This interface handles the It ensures that the correct driver
communications with the is used to access each data
database source.
Database is a
collection of
organized
information
Reference: http://awesomedevryu.blogspot.in/2014/12/jdbc-jdbc.html
8
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".
9
JDBC Driver
https://newcircle.com/bookshelf/java_fundamentals_tutorial/jdbc
10
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
11
JDBC Driver: Type 1 (JDBC-ODBC Driver)
https://www.tutorialspoint.com/jdbc/jdbc-driver-types.htm
12
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Advantages :
• Allow to communicate with all database
supported by odbc driver
• It is vendor independent driver
Disadvantages:
• Decrease the execution speed
• Dependent on the odbc driver
• Require odbc binary code or odbc client library
• Uses java native interface to make odbc call
13
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.
• The vendor-specific driver must be installed on each
client machine.
• E.g. Oracle OCI driver is a type 2 driver.
14
JDBC Driver: Type 2 (Native Code Driver)
https://www.tutorialspoint.com/jdbc/jdbc-driver-types.htm
15
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.
16
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, 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.
17
JDBC Driver: Type 3 (Java Protocol)
https://www.tutorialspoint.com/jdbc/jdbc-driver-types.htm
18
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. The client need not be changed for a
new database.
• A single driver can handle any database, provided the middleware
supports it.
• E.g.: IDA Server
Disadvantages
• 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.
19
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.
• They install inside the Java Virtual Machine of the client.
• This kind of driver is extremely flexible, you don't need to
install special software on the client or server.
20
JDBC Driver: Type 4 (Database Protocol)
https://www.tutorialspoint.com/jdbc/jdbc-driver-types.htm
21
JDBC Driver: Type 4 (Database Protocol)
Advantages
• Completely implemented in Java to achieve platform
independence.
• These drivers don't translate the requests into an intermediary
format (such as ODBC).
• The client application connects directly to the database server.
• No translation or middleware layers are used, improving
performance.
• The JVM can manage all aspects of the application-to-database
connection.
Disadvantages
• Drivers are database specific, as different database vendors use
widely different (and usually proprietary) network protocols.
22
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.
23
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]
24
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
Exe. Slowest among Faster Compared Faster Compared Fastest among all
Speed all to Type1 to Type1 & Type2
Driver Thick Driver Thick Driver Thin Driver Thin Driver
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.
26
JDBC Components
The JDBC API provides the following interfaces and classes
Package java.sql
It acts as an interface between user and drivers.
It keeps track of the drivers that are available
and handles establishing a connection between
Class
database application.
JDBC Package
java.sql
28
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
29
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:
Class.forName("com.mysql.jdbc.Dri
ver”);
30
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
31
Step 2: Connection to DBMS
Syntax:
Connection conn =
DriverManager.getConnection(URL,
USER, PASS);
Example:
Connection conn = DriverManager.getConnection
(“jdbc:mysql://localhost:3306/gtu","root",“pwd”);
32
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.
Interface is used for Statement createStatement()
general-purpose access to your throws SQLException
database, when using static SQL Creates a Statement object for sending
Statement
statements at runtime. SQL statements to the database.
st=con.createStatement();
33
Step 3:Executing Statement
• Once you've created a Statement object, you
can then use it to execute an SQL statement
with one of its three execute methods.
ResultSet executeQuery(String sql) Returns a ResultSet object. Use this method
throws SQLException when you expect to get a result set, as you
would with a SELECT statement.
Boolean execute(String sql) Returns a boolean value of true if a ResultSet
throws SQLException object can be retrieved; otherwise, it returns
false.
int executeUpdate(String sql) Returns the number of rows affected by the
throws SQLException execution of the SQL statement.
for example, an INSERT, UPDATE, or DELETE
statement.
34
Step 3: Executing Statement
Syntax:
ResultSet rs=st.executeQuery(“query”);
It holds data retrieved from a Returns a ResultSet object. Use this
database after you execute an SQL method when you expect to get a
query using Statement objects. It result set, as you would with a
acts as an iterator to allow you to SELECT statement.
move through its data.
Example
ResultSet rs = stmt.executeQuery
("SELECT * from diet");
35
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
ResultSet rs
("SELECT * from diet");
Enr_no Name Branch
601 abc ce
602 pqr me
Database
603 rst ec
604 def Ci
36
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
37
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
38
Processing data returned by the DBMS
Returns the value of
• Example specified Column number
while(rs.next())
{
System.out.println(rs.getString(1
));
System.out.println(rs.getInt(emp_
Returns the value of specified Column name
id);
}
39
Step 5:Terminating Connection with DBMS
Example
Releases this Statement object's
rs.close(); database and JDBC resources
immediately
st.close();
Releases this Connection object's
database and JDBC resources
con.close(); immediately
40
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>
41
JDBC Program
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu",
“root”, “pwd”);
ResultSet rs = stmt.executeQuery("SELECT
* from diet");
while(rs.next())
System.out.print(rs.getString(1));
stmt.close();
conn.close();
42
First JDBC Program
1. import java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
Database name
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");
Table name
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
43
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.
Use the for general-purpose access to
your database.
java.sql interface Useful for static SQL statements.
Cannot accept parameters.
Statement
Use the when you plan to use the SQL
statements many times. The
PreparedStatement interface accepts input
PreparedStatement parameters at runtime.
Table Name
45
Parameter 2
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 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.
46
Prepared Statement
create table gtu.DietStudent
•( Now to create table in mysql.
Enr_no VARCHAR(10) not null
Name VARCHAR(20),
Branch VARCHAR(10),
Division VARCHAR(10),
primary key (Enr_no)
)
47
Example of PreparedStatement that inserts the record
1. import java.sql.*;
2. public class PreparedInsert {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
8. String query="insert into dietstudent values(?,?,?,?)";
9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, "14092"); //Enr_no
11. ps.setString(2, "abc_comp"); //Name
12. ps.setString(3, "computer"); //Branch
13. ps.setString(4, "cx"); //Division
14. int i=ps.executeUpdate();
15. System.out.println("no. of rows updated ="+i);
16. ps.close();
17. conn.close();
18. }catch(Exception e){System.out.println(e.toString());}
19. }//PSVM
20. }//class
48
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.
49
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.
50
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.
51
Callable Statement
• Create mysql procedure to get book title for
Table: book
given ISBN number.
52
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");
13. cs.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class
53
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
3. Update methods Used to update the data in the columns of the current
database as well.
54
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
55
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.
56
ResultSet: Update methods
void updateString(int col_Index, String s) Changes the String in the specified column to
throws SQLException the value of s.
57
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.
58
Concurrency of ResultSet
Concurrency Description
ResultSet.CONCUR_READ_ONL Creates a read-only result set.
Y
ResultSet.CONCUR_UPDATABL Creates an updateable result set. Default
Type
E
59
ResultSet
try {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
60
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.
61
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
String getTableName(int index) it returns the table name for the specified column
throws SQLException index.
62
ResultSetMetaData
1. import java.sql.*;
2. public class MetadataDemo {
3. public static void main(String[] args) {
4. try {Class.forName("com.mysql.jdbc.Driver");
5. Connection conn= DriverManager.getConnection
6. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
7. Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from gtu");
9. ResultSetMetaData rsmd=rs.getMetaData();
10. System.out.println("Total columns: "+rsmd.getColumnCount());
11. System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
12. System.out.println("Column Type Name of 1st column:“
+rsmd.getColumnTypeName(1));
13. stmt.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class
63
Executing SQL updates
1. import java.sql.*;
2. class UpdateDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. Statement stmt=con.createStatement();
8. String query="update diet set Name='abc601' where
Enr_no=601";
9. int i=stmt.executeUpdate(query);
10. System.out.println("total no. of rows updated="+i);
11. stmt.close();
12. con.close();
13. }catch(Exception e){ System.out.println(e);}
14. } }
64
Transaction Management
65
Transaction Management
• In JDBC, Connection interface provides
methods to manage transaction.
66
Transaction Management:commit
1. import java.sql.*;
2. class CommitDemo{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/GTU","root","root");
8. con.setAutoCommit(false);//bydefault it is true
9. Statement stmt=con.createStatement();
10. int i=stmt.executeUpdate("insert into diet
values(605,'def','ci')");
11. System.out.println("no. of rows inserted="+i);
12. con.commit();//commit transaction
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }}
67
Transaction Management:rollback
1. import java.sql.*;
2. class RollbackDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into diet
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into diet
values(607,'mno','ch')");
12. System.out.println("no. of rows inserted="+i);
13. con.rollback(); //Rollback Transaction
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }} 68
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.
70
IMP Questions: GTU
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]
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]
71