SlideShare a Scribd company logo
Amity School of Engineering &
Technology
B. Tech (CSE), Semester 6
Subject: Advanced Java Programming
Course Code: IT404
MODULE-1
Amity School of Engineering and Technology
2
Unit-1: 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
2
3
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
3
4
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
4
5
Introduction: JDBC
Example
Oracle
MS Access
My SQL
SQL Server
..
.
5
JDBC is an API used to
communicate Java application to
database in database independent
and platform independent
manner.
JDBC (Java Database Connectivity) is used to
connect java application with database.
It provides classes and interfaces
to connect or communicate Java
application with database.
6
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.
6
7
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
7
8
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.
8
Introduction: JDBC API
 JDBC API allows java programs to
i. Make a connection with database
ii. Creating SQL statements
iii. Execute SQL statement
iv. Viewing & Modifying the resulting records
1. Open a Connection
2. Send a statement
3. Retrieve results
4. Close a connection 1. Create a connection
Session
2. Execute statement
3. Send results
4. Close the session
Java Application
DBMS Engine
Java DB API
10
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
10
11
The JDBC Connectivity Model
JAVA
Application
JDBC API
JDBC Driver
Database
11
12
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
13
JDBC Architecture
Java Application
JDBC API
JDBC Driver
Manager
JDBC Driver JDBC Driver JDBC Driver
Oracle SQL Server
ODBC Data
Source
A Java program that runs stand
alone in a client or server.
It provides classes & interfaces
to connect or communicate
Java application with database.
This class manages a list of
database drivers.
It ensures that the correct
driver is used to access each
data source.
This interface handles the
communications with the
database
Database is a
collection of
organized
information
14
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
15
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".
15
16
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
16
17
JDBC Driver: Type 1 (JDBC-ODBC Driver)
17
Application Code
Type 1
JDBC ODBC Bridge
ODBC
Driver
DB Vendor
Driver
Local
DBMS
Local Computer
Java Application
Database Server
Vendor Specific Protocol Network Communication
18
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.
18
19
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
19
20
JDBC Driver: Type 2 (Native Code Driver)
20
Application Code
Type 2
Native API
DB Vendor Driver
Local
DBMS
Local Computer
Java Application
Database Server
Vendor Specific Protocol Network Communication
21
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).
21
22
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.
22
23
JDBC Driver: Type 3 (Java Protocol)
23
Application Code
Type 3
JDBC-Net pure Java
JDBC Type 1 Driver
Local Computer
Java Application
Database Server
Vendor Specific Protocol Network Communication
JDBC Type 2 Driver
JDBC Type 4 Driver
Middleware Server
24
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
24
25
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.
25
26
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.
26
27
JDBC Driver: Type 4 (Database Protocol)
27
Application Code
Type 4
100% Pure Java Local
DBMS
Local Computer
Java Application
Database Server
Vendor Specific Protocol Network Communication
28
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.
28
29
JDBC Driver
Thin Driver You can connect to a database without the client installed on your
machine. E.g. Type 4.
29
Thick Driver Thick client would need the client installation.
E.g. Type 1 and Type 2.
30
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
30
Name: JDBC-ODBC
Bridge
Native Code
Driver/ JNI
Java Protocol/
Middleware
Database Protocol
Vendor
Specific:
No Yes No Yes
Portable No No Yes Yes
Working JDBC-> ODBC
call
ODBC -> native
call
JDBC call -> native
specific call
JDBC call ->
middleware
specific.
Middleware ->
native call
JDBC call ->DB
specific call
Pure
Java
Driver
No No Yes Yes
Multiple
DB
Yes
[only ODBC
supported DB]
No Yes
[DB Driver should
be in middleware]
No
31
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
31
Name: JDBC-ODBC
Bridge
Native Code
Driver/ JNI
Java Protocol/
Middleware
Database Protocol
Example MS Access Oracle OCI driver IDA Server MySQL
Executio
n Speed
Slowest among
all
Faster Compared
to Type1
Slower Compared
to Type2
Fastest among all
Driver Thick Driver Thick Driver Thin Driver Thin Driver
32
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.
32
33
JDBC with different RDBMS
33
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
SQLServer com.microsoft.sqlserver.jdbc.SQLServ
erDriver
jdbc:microsoft:sqlserver:
//hostname:1433;DatabaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
Derby org.apache.derby.jdbc.ClientDriver "jdbc:derby://localhost:1527/
DB;user=APP;password=APP"
34
Questions : JDBC
1 What is JDBC? List out all various types of JDBC Driver. Explain
Thick and Thin driver. Write code snippet for each type of JDBC
connection. Comment on selection of driver. [7 Marks]
Sum’16
34
2 What is JDBC? Explain the types of JDBC drivers? Write a code
snippet for each type of JDBC connection. [7 Marks]
Win’16
3 Explain JDBC driver types in detail.[7 Marks] Sum’17
4 List the different types of JDBC drivers. Compare the various
driver types for their advantages and disadvantages.
Sum’18
5 List different types of JDBC drivers and explain any two of them.
[7 Marks]
Win’18
6 List types of diver used in JDBC. Explain Thin driver. [3 Marks] Win’19
35
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
35
36
JDBC Components
The JDBC API provides the following interfaces and classes
DriverManager
Connection
Driver
Statement
SQLException
ResultSet
It acts as an interface between user and
drivers. It keeps track of the drivers that
are available and handles establishing a
connection between a database and the
appropriate driver.
Class
Interface
Exception
Package java.sql
This interface handles the
communications with the database
server. Driver interface provides vendor-
specific implementations of the abstract
classes provided by the JDBC API.
This Interface is the session between java
application and database. It contains all
methods for contacting a database.
This class handles any errors that occur in a
database application.
This interface is used to submit the SQL
statements to the database.
These objects hold data retrieved from a
database after you execute an SQL query
using Statement objects. It acts as an
iterator to allow you to move through its
data.
36
37
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
37
38
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.
38
39
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
39
40
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
40
41
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.Driver”);
41
Class that represent
classes and interfaces in
a running Java
application.
Returns the Class object associated with the
class or interface with the given string name.
Main Pakage
Sub-Pakage
Class.forName() is used
for loading class dynamically
It is used to initiate
Driver at runtime
42
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
42
public static Connection
getConnection(String url) throws
SQLException
Attempts to establish a connection to the given
database URL. The DriverManager attempts to
select an appropriate driver from the set of
registered JDBC drivers.
public static Connection
getConnection(String url,
String user,
String password
)
throws SQLException
Attempts to establish a connection to the given
database URL.
url - a database url of the
form jdbc:subprotocol:subname
user - the database user on whose behalf the
connection is being made
password - the user's password
43
Step 2: Connection to DBMS
Syntax:
Connection conn=
DriverManager.getConnection(URL,USER_NM,PASS)
;
Example:
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/amity","root", “ ");
43
Interface of java.sql package
Class of java.sql package
Database Name
44
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();
44
Interface is used for general-
purpose access to your database,
when using static SQL statements at
runtime.
Statement createStatement()
throws SQLException
Creates a Statement object for sending
SQL statements to the database.
45
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.
45
ResultSet executeQuery(String sql)
throws SQLException
Returns a ResultSet object. Use this method
when you expect to get a result set, as you
would with a SELECT statement.
Boolean execute(String sql)
throws SQLException
Returns a boolean value of true if a ResultSet
object can be retrieved; otherwise, it returns
false.
int executeUpdate(String sql)
throws SQLException
Returns the number of rows affected by the
execution of the SQL statement.
for example, an INSERT, UPDATE, or DELETE
statement.
46
Step 3: Executing Statement
Syntax:
ResultSet rs=st.executeQuery(“query”);
Example
ResultSet rs = stmt.executeQuery
("SELECT * from thirdcse");
46
It holds data retrieved from a
database after you execute an SQL
query using Statement objects. It
acts as an iterator to allow you to
move through its data.
Returns a ResultSet object. Use this
method when you expect to get a
result set, as you would with a
SELECT statement.
47
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * from
babaria");
47
Database
Enr_no Name Branch
601 abc ce
602 pqr me
603 rst ec
604 def Ci
ResultSet rs
48
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * FROM thirdcse WHERE
rollno = '"+sid+"'");
48
Database
Enr_no Name Branch
601 abc ce
602 pqr me
ResultSet rs
49
Step 4:Processing data returned by the DBMS
 Method: Resultset
49
boolean next()
Throws SQLException
Moves the cursor forward one row from its
current position.
String getString
(int col_Index)
throws SQLException
Retrieves the value of the designated column in
the current row of this ResultSet object as
a String
int getInt
(int columnIndex) throws
SQLException
Returns the int in the current row in the
specified column index.
String getString
(String col_Label)
throws SQLException
Retrieves the value of the designated column in
the current row of this ResultSet object as
a String in the Java programming language.
int getInt
(String columnLabel)
throws SQLException
Retrieves the value of the designated column in
the current row
50
Processing data returned by the DBMS
 Example
while(rs.next())
{
res="The student name
is"+rs.getString(2)+" mark
is"+rs.getInt(4); }
50
Returns the v
specified Column
51
Step 5:Terminating Connection with DBMS
 The connection of DBMS is terminated by using close() method.
Example
rs.close();
st.close();
con.close();
51
Releases this ResultSet object's
database and JDBC resources
immediately
Releases this Statement object's
database and JDBC resources
immediately
Releases this Connection object's
database and JDBC resources
immediately
52
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
52
53
JDBC Program
53
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection
("jdbc:mysql://localhost:3306/babaria",
“root”, “ ”);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
* from
babaria");
while(rs.next())
System.out.print(rs.getString(1));
stmt.close();
conn.close();
54
First JDBC Program
54
55
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
55
56
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.
56
Statement
PreparedStatement
CallableStatement
java.sql interface
Used when you want to access the
database stored procedures. The
CallableStatement interface can also
accept runtime input parameters.
Used when you plan to use the SQL
statements multiple times. The
PreparedStatement interface accepts
input parameters at runtime.
Used for general-purpose access to your
database.
Useful for static SQL statements.
Cannot accept parameters.
57
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.
Example
String query="insert into thirdcse values(?,?,?)";
57
Table Name
Parameter 2
Parameter 1
Parameter 3
58
Methods of PreparedStatement interface
58
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.
59
Prepared Statement
 Now to create table in mysql.
59
CREATE TABLE
`babaria`.`thirdcse` ( `rollno` VARCHAR
(10) NOT NULL , `name` VARCHAR(20) NOT
NULL , `address` VARCHAR(30) NOT
NULL , `mark` INT(10) NOT
NULL , PRIMARY KEY (`rollno`))
regno name address mobile
60
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/babaria", "root",“
");
8. String query="insert into thirdcse values(?,?,?,?)";
9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, “A1003"); //rollno
11. ps.setString(2, “jinu"); //Name
12. ps.setString(3, “Delhi"); //address
13. ps.setString(4, “20"); //mark
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 60
61
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.
61
62
Exam Question
1. Show the use of PreparedStatement object to run
precompiled SQL statement. Also write example of
java snippet for PreparedStaement.[7]
Sum’16
2. Explain the use of PreparedStatement with
appropriate example.[7]
Win’16
3. Explain role of Prepared Statement with example.[7] Sum’17
4. Write a program to insert student records to
database using prepared statement.[7]
Win’17
5. Explain the use of the PreparedStatement object of
the JDBC with an appropriate example.[7]
Win’18
6. Write difference between statement and prepared
statement interface.[3]
Win’19
62
63
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
63
64
Method: ResultSet
Categories
64
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.
65
ResultSet: Navigational methods
65
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()
throws SQLException
Moves the cursor to the previous row. This method
returns false if the 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.
66
ResultSet: Get methods
66
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)
throws SQLException
Retrieves the value of the designated column in
the current row of this ResultSet object as
a String in the Java programming language.
String getString(int columnIndex)
throws SQLException
Retrieves the value of the designated column in
the current row of this ResultSet object as
a String in the Java programming language.
67
ResultSet: Update methods
67
void updateString(int col_Index, String s)
throws SQLException
Changes the String in the specified column to
the value of s.
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)
throws SQLException
Updates the designated column with
a double value.
68
Types of ResultSet
68
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.
69
Concurrency of ResultSet
69
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set.
Default
Type
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
70
ResultSet
try {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
....
}
70
ResultSet Type
ResultSet Concurrency
71
Exam Question
1. What is ResultSet interface. Write various method for
ResultSet interface. Write a code to update record
using this interface.[7]
Win’19
71
72
Unit-1: 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
72
73
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.
73
74
Method: ResultSetMetaData
74
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.
75
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/babaria", "root",“");
7. Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from thirdcse");
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
75
76
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.
76
77
DatabaseMetadata
1. Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/temp6","root","root");
2. DatabaseMetaData dbmd=con.getMetaData();
3. System.out.println("getDatabaseProductName:“
+dbmd.getDatabaseProductName());
4. System.out.println("getDatabaseProductVersion():“
+dbmd.getDatabaseProductVersion());
5. System.out.println("getDriverName():"+dbmd.getDriverName());
6. System.out.println("getDriverVersion():“
+dbmd.getDriverVersion());
7. System.out.println("getURL():"+dbmd.getURL());
8. System.out.println("getUserName():"+dbmd.getUserName());
77
78
Exam Question
1. Explain use of DatabaseMetaData with example.[3] Sum’18
Win’18
2. Explain ResultSetMetaData with suitable program.
[3]
Win’18
78
79
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
79
80
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/babaria","root","");
7. Statement stmt=con.createStatement();
8. String query="update thirdcse set name=‘sheena' where
rollno=A1002";
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.} }
80
81
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
81
82
Transaction Management
82
Transaction
Initial State
Commit
Rollback
Transaction Succeed
Transaction Failed
83
Transaction Management
 In JDBC, Connection interface provides methods to manage
transaction.
83
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.
84
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/babaria","root","");
8. con.setAutoCommit(false);//bydefault it is true
9. Statement stmt=con.createStatement();
10. int i=stmt.executeUpdate("insert into thirdcse
values(‘A1006’,‘sri',‘goa‘,’25’ )");
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.}}
84
85
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/babaria","root","");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into thirdcse values
(‘A1007’,‘varna',‘nagland‘,’55’ )");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into thirdcse values
('A1007',‘vinay',‘bhopal',‘50')"
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.}}
85
86
Important Questions:
1. What is JDBC?
List out different types of JDBC driver and explain role of each.
Write code snippet for each type of JDBC connection.
Explain Thick and Thin driver.
Comment on selection of driver.
[Sum -16]
[Win -16]
[Sum -18]
[Win -18]
[Win -19]
86
2. Explain Prepared statements with suitable example [Sum -16]
[Win -16]
[Win -17]
[Win -18]
4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16]
3. Give the use of Statement, PreparedStatement and CallableStatement
object. Write code to insert three records into student table using
PreparedStatement (assume student table with Name, RollNo, and Branch
field).
[Win -14]
5. Discuss CallableStatement with example. [Win -17]
[Win -18]
6. What is ResultSet interface. Write various method for ResultSet interface.
Write a code to update record using this interface.
[Win -19]
87
Important Questions:
7. Explain JDBC Transaction Management in detail. [Win -19]
8. Explain use of DatabaseMetaData with example. [Sum -18]
[Win -18]
9. Explain ResultSetMetaData with suitable program. [Win -18]
10. Write a sample code to store image in Database. [Win -19]
87
J2EE Architecture
• A J2EE application contains four components or
tiers: Presentation, Application, Business, and
Resource adapter components.
• The presentation component is the client side
component that is visible to the client and runs on
the client’s server.
• The Application component is web side layer that
runs on the J2EE server.
• The business component is the business layer
which includes server-side business logic such as
JavaBeans, and it is also run on the J2EE server.
• The resource adaptor component comprises an
enterprise information system.
90
Servlet with JDBC
91
Servlet with JDBC
1. import java.io.*;
2. import java.sql.*;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class JDBCServlet extends HttpServlet
6. {
7. public void doGet(HttpServletRequest request,
HttpServletResponse response)
8. throws ServletException,IOException
9. { response.setContentType("text/html");
10. PrintWriter out=response.getWriter();
//Program continued in next slide…
...
92
Servlet with JDBC
11. try{
12. Class.forName("com.mysql.jdbc.Driver");
13. Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ajava","root","");
14. Statement st=con.createStatement();
15. ResultSet rs=st.executeQuery("select * from cxcy");
16. while(rs.next())
17. { out.println("<p>"+rs.getInt(1));
18. out.println(rs.getString(2));
19. out.println(rs.getString(3)+"</p>");
20. }
21. }catch(Exception e)
22. {out.println("<p>inside exception"+e.toString()+"</p>");}
23. }//doGet()
24. }//Class

More Related Content

PPTX
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
PPTX
3160707_AJava_GTU_Study_Material_Presentations_Unit-2_17032021071519AM.pptx
PPT
java database connection (jdbc)
PPTX
Chapter2 j2ee
PPTX
Advanced JAVA
PPT
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
3160707_AJava_GTU_Study_Material_Presentations_Unit-2_17032021071519AM.pptx
java database connection (jdbc)
Chapter2 j2ee
Advanced JAVA

Similar to UNIT 1 PPT- FINAL.pptx Advance Java JDBC (20)

PPT
4-INTERDUCATION TO JDBC-2019.ppt
PPTX
Chapter_4_-_JDBC[1].pptx
PPTX
java.pptx
PDF
PPTX
Jdbc
PPTX
Jdbc driver types
DOC
jdbc document
PPTX
Java Database Connectivity (JDBC)
PPT
JDBC java database connectivity with dbms
PPT
JDBC Architecture and Drivers
PPT
Jdbc complete
PPTX
Java jdbc
PPT
Unit 1 Advance Java - JDBC.ppt
PPT
PPTX
java 4 Part 1 computer science.pptx
PPTX
Java database connectivity with MySql
PPTX
Java database connectivity with MySql
PDF
unit8_jdbc.pdf mysql and java jdbc connection
PDF
JDBC with MySQL.pdf
PDF
JDBC with MySQL.pdf
4-INTERDUCATION TO JDBC-2019.ppt
Chapter_4_-_JDBC[1].pptx
java.pptx
Jdbc
Jdbc driver types
jdbc document
Java Database Connectivity (JDBC)
JDBC java database connectivity with dbms
JDBC Architecture and Drivers
Jdbc complete
Java jdbc
Unit 1 Advance Java - JDBC.ppt
java 4 Part 1 computer science.pptx
Java database connectivity with MySql
Java database connectivity with MySql
unit8_jdbc.pdf mysql and java jdbc connection
JDBC with MySQL.pdf
JDBC with MySQL.pdf
Ad

Recently uploaded (20)

PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
Mechanical Engineering MATERIALS Selection
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PDF
composite construction of structures.pdf
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
PPT on Performance Review to get promotions
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
web development for engineering and engineering
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Well-logging-methods_new................
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPT
Project quality management in manufacturing
PPTX
Sustainable Sites - Green Building Construction
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mechanical Engineering MATERIALS Selection
Embodied AI: Ushering in the Next Era of Intelligent Systems
Operating System & Kernel Study Guide-1 - converted.pdf
Lesson 3_Tessellation.pptx finite Mathematics
composite construction of structures.pdf
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT on Performance Review to get promotions
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Foundation to blockchain - A guide to Blockchain Tech
web development for engineering and engineering
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Well-logging-methods_new................
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Project quality management in manufacturing
Sustainable Sites - Green Building Construction
Ad

UNIT 1 PPT- FINAL.pptx Advance Java JDBC

  • 1. Amity School of Engineering & Technology B. Tech (CSE), Semester 6 Subject: Advanced Java Programming Course Code: IT404 MODULE-1 Amity School of Engineering and Technology
  • 2. 2 Unit-1: 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 2
  • 3. 3 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 3
  • 4. 4 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 4
  • 5. 5 Introduction: JDBC Example Oracle MS Access My SQL SQL Server .. . 5 JDBC is an API used to communicate Java application to database in database independent and platform independent manner. JDBC (Java Database Connectivity) is used to connect java application with database. It provides classes and interfaces to connect or communicate Java application with database.
  • 6. 6 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. 6
  • 7. 7 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 7
  • 8. 8 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. 8
  • 9. Introduction: JDBC API  JDBC API allows java programs to i. Make a connection with database ii. Creating SQL statements iii. Execute SQL statement iv. Viewing & Modifying the resulting records 1. Open a Connection 2. Send a statement 3. Retrieve results 4. Close a connection 1. Create a connection Session 2. Execute statement 3. Send results 4. Close the session Java Application DBMS Engine Java DB API
  • 10. 10 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 10
  • 11. 11 The JDBC Connectivity Model JAVA Application JDBC API JDBC Driver Database 11
  • 12. 12 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
  • 13. 13 JDBC Architecture Java Application JDBC API JDBC Driver Manager JDBC Driver JDBC Driver JDBC Driver Oracle SQL Server ODBC Data Source A Java program that runs stand alone in a client or server. It provides classes & interfaces to connect or communicate Java application with database. This class manages a list of database drivers. It ensures that the correct driver is used to access each data source. This interface handles the communications with the database Database is a collection of organized information
  • 14. 14 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
  • 15. 15 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". 15
  • 16. 16 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 16
  • 17. 17 JDBC Driver: Type 1 (JDBC-ODBC Driver) 17 Application Code Type 1 JDBC ODBC Bridge ODBC Driver DB Vendor Driver Local DBMS Local Computer Java Application Database Server Vendor Specific Protocol Network Communication
  • 18. 18 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. 18
  • 19. 19 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 19
  • 20. 20 JDBC Driver: Type 2 (Native Code Driver) 20 Application Code Type 2 Native API DB Vendor Driver Local DBMS Local Computer Java Application Database Server Vendor Specific Protocol Network Communication
  • 21. 21 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). 21
  • 22. 22 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. 22
  • 23. 23 JDBC Driver: Type 3 (Java Protocol) 23 Application Code Type 3 JDBC-Net pure Java JDBC Type 1 Driver Local Computer Java Application Database Server Vendor Specific Protocol Network Communication JDBC Type 2 Driver JDBC Type 4 Driver Middleware Server
  • 24. 24 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 24
  • 25. 25 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. 25
  • 26. 26 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. 26
  • 27. 27 JDBC Driver: Type 4 (Database Protocol) 27 Application Code Type 4 100% Pure Java Local DBMS Local Computer Java Application Database Server Vendor Specific Protocol Network Communication
  • 28. 28 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. 28
  • 29. 29 JDBC Driver Thin Driver You can connect to a database without the client installed on your machine. E.g. Type 4. 29 Thick Driver Thick client would need the client installation. E.g. Type 1 and Type 2.
  • 30. 30 Comparison between JDBC Drivers Type: Type 1 Type 2 Type 3 Type 4 30 Name: JDBC-ODBC Bridge Native Code Driver/ JNI Java Protocol/ Middleware Database Protocol Vendor Specific: No Yes No Yes Portable No No Yes Yes Working JDBC-> ODBC call ODBC -> native call JDBC call -> native specific call JDBC call -> middleware specific. Middleware -> native call JDBC call ->DB specific call Pure Java Driver No No Yes Yes Multiple DB Yes [only ODBC supported DB] No Yes [DB Driver should be in middleware] No
  • 31. 31 Comparison between JDBC Drivers Type: Type 1 Type 2 Type 3 Type 4 31 Name: JDBC-ODBC Bridge Native Code Driver/ JNI Java Protocol/ Middleware Database Protocol Example MS Access Oracle OCI driver IDA Server MySQL Executio n Speed Slowest among all Faster Compared to Type1 Slower Compared to Type2 Fastest among all Driver Thick Driver Thick Driver Thin Driver Thin Driver
  • 32. 32 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. 32
  • 33. 33 JDBC with different RDBMS 33 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 SQLServer com.microsoft.sqlserver.jdbc.SQLServ erDriver jdbc:microsoft:sqlserver: //hostname:1433;DatabaseName Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port> SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName Derby org.apache.derby.jdbc.ClientDriver "jdbc:derby://localhost:1527/ DB;user=APP;password=APP"
  • 34. 34 Questions : JDBC 1 What is JDBC? List out all various types of JDBC Driver. Explain Thick and Thin driver. Write code snippet for each type of JDBC connection. Comment on selection of driver. [7 Marks] Sum’16 34 2 What is JDBC? Explain the types of JDBC drivers? Write a code snippet for each type of JDBC connection. [7 Marks] Win’16 3 Explain JDBC driver types in detail.[7 Marks] Sum’17 4 List the different types of JDBC drivers. Compare the various driver types for their advantages and disadvantages. Sum’18 5 List different types of JDBC drivers and explain any two of them. [7 Marks] Win’18 6 List types of diver used in JDBC. Explain Thin driver. [3 Marks] Win’19
  • 35. 35 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 35
  • 36. 36 JDBC Components The JDBC API provides the following interfaces and classes DriverManager Connection Driver Statement SQLException ResultSet It acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. Class Interface Exception Package java.sql This interface handles the communications with the database server. Driver interface provides vendor- specific implementations of the abstract classes provided by the JDBC API. This Interface is the session between java application and database. It contains all methods for contacting a database. This class handles any errors that occur in a database application. This interface is used to submit the SQL statements to the database. These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. 36
  • 37. 37 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 37
  • 38. 38 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. 38
  • 39. 39 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 39
  • 40. 40 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 40
  • 41. 41 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.Driver”); 41 Class that represent classes and interfaces in a running Java application. Returns the Class object associated with the class or interface with the given string name. Main Pakage Sub-Pakage Class.forName() is used for loading class dynamically It is used to initiate Driver at runtime
  • 42. 42 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 42 public static Connection getConnection(String url) throws SQLException Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers. public static Connection getConnection(String url, String user, String password ) throws SQLException Attempts to establish a connection to the given database URL. url - a database url of the form jdbc:subprotocol:subname user - the database user on whose behalf the connection is being made password - the user's password
  • 43. 43 Step 2: Connection to DBMS Syntax: Connection conn= DriverManager.getConnection(URL,USER_NM,PASS) ; Example: Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/amity","root", “ "); 43 Interface of java.sql package Class of java.sql package Database Name
  • 44. 44 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(); 44 Interface is used for general- purpose access to your database, when using static SQL statements at runtime. Statement createStatement() throws SQLException Creates a Statement object for sending SQL statements to the database.
  • 45. 45 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. 45 ResultSet executeQuery(String sql) throws SQLException Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. Boolean execute(String sql) throws SQLException Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. int executeUpdate(String sql) throws SQLException Returns the number of rows affected by the execution of the SQL statement. for example, an INSERT, UPDATE, or DELETE statement.
  • 46. 46 Step 3: Executing Statement Syntax: ResultSet rs=st.executeQuery(“query”); Example ResultSet rs = stmt.executeQuery ("SELECT * from thirdcse"); 46 It holds data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.
  • 47. 47 Step 3: Executing Statement ResultSet rs = stmt.executeQuery ("SELECT * from babaria"); 47 Database Enr_no Name Branch 601 abc ce 602 pqr me 603 rst ec 604 def Ci ResultSet rs
  • 48. 48 Step 3: Executing Statement ResultSet rs = stmt.executeQuery ("SELECT * FROM thirdcse WHERE rollno = '"+sid+"'"); 48 Database Enr_no Name Branch 601 abc ce 602 pqr me ResultSet rs
  • 49. 49 Step 4:Processing data returned by the DBMS  Method: Resultset 49 boolean next() Throws SQLException Moves the cursor forward one row from its current position. String getString (int col_Index) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String int getInt (int columnIndex) throws SQLException Returns the int in the current row in the specified column index. String getString (String col_Label) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. int getInt (String columnLabel) throws SQLException Retrieves the value of the designated column in the current row
  • 50. 50 Processing data returned by the DBMS  Example while(rs.next()) { res="The student name is"+rs.getString(2)+" mark is"+rs.getInt(4); } 50 Returns the v specified Column
  • 51. 51 Step 5:Terminating Connection with DBMS  The connection of DBMS is terminated by using close() method. Example rs.close(); st.close(); con.close(); 51 Releases this ResultSet object's database and JDBC resources immediately Releases this Statement object's database and JDBC resources immediately Releases this Connection object's database and JDBC resources immediately
  • 52. 52 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 52
  • 53. 53 JDBC Program 53 Class.forName("com.mysql.jdbc.Driver"); Connection conn= DriverManager.getConnection ("jdbc:mysql://localhost:3306/babaria", “root”, “ ”); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * from babaria"); while(rs.next()) System.out.print(rs.getString(1)); stmt.close(); conn.close();
  • 55. 55 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 55
  • 56. 56 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. 56 Statement PreparedStatement CallableStatement java.sql interface Used when you want to access the database stored procedures. The CallableStatement interface can also accept runtime input parameters. Used when you plan to use the SQL statements multiple times. The PreparedStatement interface accepts input parameters at runtime. Used for general-purpose access to your database. Useful for static SQL statements. Cannot accept parameters.
  • 57. 57 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. Example String query="insert into thirdcse values(?,?,?)"; 57 Table Name Parameter 2 Parameter 1 Parameter 3
  • 58. 58 Methods of PreparedStatement interface 58 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.
  • 59. 59 Prepared Statement  Now to create table in mysql. 59 CREATE TABLE `babaria`.`thirdcse` ( `rollno` VARCHAR (10) NOT NULL , `name` VARCHAR(20) NOT NULL , `address` VARCHAR(30) NOT NULL , `mark` INT(10) NOT NULL , PRIMARY KEY (`rollno`)) regno name address mobile
  • 60. 60 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/babaria", "root",“ "); 8. String query="insert into thirdcse values(?,?,?,?)"; 9. PreparedStatement ps=conn.prepareStatement(query); 10. ps.setString(1, “A1003"); //rollno 11. ps.setString(2, “jinu"); //Name 12. ps.setString(3, “Delhi"); //address 13. ps.setString(4, “20"); //mark 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 60
  • 61. 61 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. 61
  • 62. 62 Exam Question 1. Show the use of PreparedStatement object to run precompiled SQL statement. Also write example of java snippet for PreparedStaement.[7] Sum’16 2. Explain the use of PreparedStatement with appropriate example.[7] Win’16 3. Explain role of Prepared Statement with example.[7] Sum’17 4. Write a program to insert student records to database using prepared statement.[7] Win’17 5. Explain the use of the PreparedStatement object of the JDBC with an appropriate example.[7] Win’18 6. Write difference between statement and prepared statement interface.[3] Win’19 62
  • 63. 63 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 63
  • 64. 64 Method: ResultSet Categories 64 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.
  • 65. 65 ResultSet: Navigational methods 65 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() throws SQLException Moves the cursor to the previous row. This method returns false if the 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.
  • 66. 66 ResultSet: Get methods 66 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) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. String getString(int columnIndex) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
  • 67. 67 ResultSet: Update methods 67 void updateString(int col_Index, String s) throws SQLException Changes the String in the specified column to the value of s. 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) throws SQLException Updates the designated column with a double value.
  • 68. 68 Types of ResultSet 68 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.
  • 69. 69 Concurrency of ResultSet 69 Concurrency Description ResultSet.CONCUR_READ_ONLY Creates a read-only result set. Default Type ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
  • 70. 70 ResultSet try { Statement stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } catch(Exception ex) { .... } 70 ResultSet Type ResultSet Concurrency
  • 71. 71 Exam Question 1. What is ResultSet interface. Write various method for ResultSet interface. Write a code to update record using this interface.[7] Win’19 71
  • 72. 72 Unit-1: 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 72
  • 73. 73 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. 73
  • 74. 74 Method: ResultSetMetaData 74 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.
  • 75. 75 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/babaria", "root",“"); 7. Statement stmt = conn.createStatement (ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY); 8. ResultSet rs = stmt.executeQuery("SELECT * from thirdcse"); 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 75
  • 76. 76 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. 76
  • 77. 77 DatabaseMetadata 1. Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/temp6","root","root"); 2. DatabaseMetaData dbmd=con.getMetaData(); 3. System.out.println("getDatabaseProductName:“ +dbmd.getDatabaseProductName()); 4. System.out.println("getDatabaseProductVersion():“ +dbmd.getDatabaseProductVersion()); 5. System.out.println("getDriverName():"+dbmd.getDriverName()); 6. System.out.println("getDriverVersion():“ +dbmd.getDriverVersion()); 7. System.out.println("getURL():"+dbmd.getURL()); 8. System.out.println("getUserName():"+dbmd.getUserName()); 77
  • 78. 78 Exam Question 1. Explain use of DatabaseMetaData with example.[3] Sum’18 Win’18 2. Explain ResultSetMetaData with suitable program. [3] Win’18 78
  • 79. 79 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 79
  • 80. 80 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/babaria","root",""); 7. Statement stmt=con.createStatement(); 8. String query="update thirdcse set name=‘sheena' where rollno=A1002"; 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.} } 80
  • 81. 81 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 81
  • 83. 83 Transaction Management  In JDBC, Connection interface provides methods to manage transaction. 83 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.
  • 84. 84 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/babaria","root",""); 8. con.setAutoCommit(false);//bydefault it is true 9. Statement stmt=con.createStatement(); 10. int i=stmt.executeUpdate("insert into thirdcse values(‘A1006’,‘sri',‘goa‘,’25’ )"); 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.}} 84
  • 85. 85 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/babaria","root",""); 7. con.setAutoCommit(false);//bydeafault it is true 8. Statement stmt=con.createStatement(); 9. int i=stmt.executeUpdate("insert into thirdcse values (‘A1007’,‘varna',‘nagland‘,’55’ )"); 10. con.commit(); //Commit Transaction 11. i+=stmt.executeUpdate("insert into thirdcse values ('A1007',‘vinay',‘bhopal',‘50')" 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.}} 85
  • 86. 86 Important Questions: 1. What is JDBC? List out different types of JDBC driver and explain role of each. Write code snippet for each type of JDBC connection. Explain Thick and Thin driver. Comment on selection of driver. [Sum -16] [Win -16] [Sum -18] [Win -18] [Win -19] 86 2. Explain Prepared statements with suitable example [Sum -16] [Win -16] [Win -17] [Win -18] 4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16] 3. Give the use of Statement, PreparedStatement and CallableStatement object. Write code to insert three records into student table using PreparedStatement (assume student table with Name, RollNo, and Branch field). [Win -14] 5. Discuss CallableStatement with example. [Win -17] [Win -18] 6. What is ResultSet interface. Write various method for ResultSet interface. Write a code to update record using this interface. [Win -19]
  • 87. 87 Important Questions: 7. Explain JDBC Transaction Management in detail. [Win -19] 8. Explain use of DatabaseMetaData with example. [Sum -18] [Win -18] 9. Explain ResultSetMetaData with suitable program. [Win -18] 10. Write a sample code to store image in Database. [Win -19] 87
  • 89. • A J2EE application contains four components or tiers: Presentation, Application, Business, and Resource adapter components. • The presentation component is the client side component that is visible to the client and runs on the client’s server. • The Application component is web side layer that runs on the J2EE server. • The business component is the business layer which includes server-side business logic such as JavaBeans, and it is also run on the J2EE server. • The resource adaptor component comprises an enterprise information system.
  • 91. 91 Servlet with JDBC 1. import java.io.*; 2. import java.sql.*; 3. import javax.servlet.*; 4. import javax.servlet.http.*; 5. public class JDBCServlet extends HttpServlet 6. { 7. public void doGet(HttpServletRequest request, HttpServletResponse response) 8. throws ServletException,IOException 9. { response.setContentType("text/html"); 10. PrintWriter out=response.getWriter(); //Program continued in next slide… ...
  • 92. 92 Servlet with JDBC 11. try{ 12. Class.forName("com.mysql.jdbc.Driver"); 13. Connection con=DriverManager.getConnection ("jdbc:mysql://localhost:3306/ajava","root",""); 14. Statement st=con.createStatement(); 15. ResultSet rs=st.executeQuery("select * from cxcy"); 16. while(rs.next()) 17. { out.println("<p>"+rs.getInt(1)); 18. out.println(rs.getString(2)); 19. out.println(rs.getString(3)+"</p>"); 20. } 21. }catch(Exception e) 22. {out.println("<p>inside exception"+e.toString()+"</p>");} 23. }//doGet() 24. }//Class

Editor's Notes

  • #5: List of Database can linked with jdbc API Oracle 11  MySQL 5.1 Sybase ASE DB2 9.7  Microsoft SQL Server 2008  PostgreSQL 8.4  http://www.benchresources.net/jdbc-driver-list-and-url-for-all-databases/
  • #24: Search Results The new names of Microsoft's Identity and Access (IDA) solutio Search Results The new names of Microsoft's Identity and Access (IDA) solutio
  • #25: Search Results The new names of Microsoft's Identity and Access (IDA) solutio Search Results The new names of Microsoft's Identity and Access (IDA) solutio
  • #26: IDA-Identity and Access
  • #36: DriverManager is a non-abstract class in JDBC API. It contains only one constructor which is declared as private, i.e this class can’t be inherited or initailzed directly
  • #41: java.lang.Class.forName() method-This method returns the class object representing the desired class.