AJ - Unit-2 - JDBC Programming
AJ - Unit-2 - JDBC Programming
Unit-2
JDBC
Programming
Reference Books
Sr. Unit Reference Book Chapter
No.
1 Java Networking The Complete Reference, Java (Seventh 20
Edition), Herbert Schild - Osbrone.
2 JDBC Programming Complete Reference J2EE by James Keogh 6,7
mcgraw publication
3 Servlet API and 7,8
Overview Professional Java Server Programming by
4 Java Server Pages Subrahmanyam Allamaraju, Cedric Buest 10,11
Wiley Publication
Reference Book:
Complete Reference J2EE by James Keogh mcgraw publication
Chapter : 6 and 7
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
4
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
5
Introduction
• Database
– Collection of data
• DBMS
– Database Management System
– Storing and organizing data
• SQL
– Relational database
– Structured Query Language
• JDBC
– Java Database Connectivity
– JDBC driver
6
Introduction: JDBC
JDBC (Java Database Connectivity) is used to It provides classes and interfaces
connect java application with database. to connect or communicate Java
application with database.
Example
Oracle
MS Access
My SQL
SQL Server
..
.
7
Introduction: JDBC
• JDBC (Java Database Connection) is the standard
method of accessing databases from Java
application.
• JDBC is a specification from Sun Microsystem
that provides a standard API for java application
to communicate with different database.
• JDBC is a platform independent interface
between relational database and java
applications.
8
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
9
What is an API?
• Application Program Interface
• A set of routines, protocols, and tools for building
software applications.
• JDBC is an API, which is used in java programming
for interacting with database.
10
Introduction: JDBC API
• JDBC API allows java programs to
i. Make a connection with database
ii. Creating SQL statements
iii. Execute SQL statement
Java Application
11
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
12
The JDBC Connectivity Model
JDBC API
JAVA
JDBC Driver
Application Database
13
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
14
JDBC Architecture
It provides classes & interfaces A Java program that runs stand
Java Application alone in a client or server.
to connect or communicate
Java application with database.
16
JDBC Driver
• API: Set of interfaces independent of the RDBMS
• Driver: RDBMS-specific implementation of API
interfaces e.g. Oracle, DB2, MySQL, etc.
17
JDBC Driver: Type1 (JDBC-ODBC Driver)
• Depends on support for ODBC
• Not portable
• Translate JDBC calls into ODBC calls and use Windows ODBC
built in drivers
• ODBC must be set up on every client
– for server side servlets ODBC must be set up on web server
• driver sun.jdbc.odbc.JdbcOdbc provided by JavaSoft with JDK
• No support from JDK 1.8 (Java 8)
E.g. MS Access
18
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Local Computer
Java Application
DB Vendor
Application Code Driver
Type 1
ODBC Local
JDBC ODBC Bridge
Driver DBMS
Database Server
19
20
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Advantages :
• Allow to communicate with all database supported by ODBC
driver
• It is vendor independent driver
Disadvantages:
• Due to large number of translations, execution speed is
decreased
• Dependent on the ODBC driver
• ODBC binary code or ODBC client library to be installed in every
client machine
• Uses java native interface to make ODBC call
Because of listed disadvantage, type1 driver is not used in
production environment. It can only be used, when database
doesn’t have any other JDBC driver implementation.
21
JDBC Driver: Type 2 (Native Code Driver)
• JDBC API calls are converted into native API calls, which
are unique to the database.
• These drivers are typically provided by the database
vendors and used in the same manner as the JDBC-ODBC
Bridge.
• Native code Driver are usually written in C, C++.
• The vendor-specific driver must be installed on each
client machine.
• Type 2 Driver is suitable to use with server side
applications.
• E.g. Oracle OCI driver, Weblogic OCI driver, Type2 for
Sybase
22
JDBC Driver: Type 2 (Native Code Driver)
Local Computer
Java Application
DB Vendor Driver
Application Code
Type 2
Native API Local
DBMS
Database Server
23
24
JDBC Driver: Type 2 (Native Code Driver)
Advantages
• As there is no implementation of JDBC-ODBC bridge,
it may be considerably faster than a Type 1 driver.
Disadvantages
• The vendor client library needs to be installed on the
client machine.
• This driver is platform dependent.
• This driver supports all java applications except
applets.
• It may increase cost of application, if it needs to run
on different platform (since we may require buying
the native libraries for all of the platform).
25
JDBC Driver: Type 3 (Java Protocol)
• Pure Java Driver
• Depends on Middleware server
• Can interface to multiple databases – Not vendor specific.
• Follows a three-tier communication approach.
• The JDBC clients use standard network sockets to communicate
with a middleware application server.
• The socket information is then translated by the middleware
application server into the call format required by the DBMS.
• This kind of driver is extremely flexible, since it requires no code
installed on the client and a single driver can actually provide
access to multiple databases.
26
JDBC Driver: Type 3 (Java Protocol)
Local Computer Middleware Server
Java Application
JDBC Type 1 Driver
Application Code
JDBC Type 2 Driver
Type 3
JDBC-Net pure Java JDBC Type 4 Driver
Database Server
27
28
JDBC Driver: Type 3 (Java Protocol)
Advantages
• Since the communication between client and the
middleware server is database independent, there is
no need for the database vendor library on the client.
• A single driver can handle any database, provided the
middleware supports it.
• We can switch from one database to other without
changing the client-side driver class, by just changing
configurations of middleware server.
• E.g.: IDS Driver, Weblogic RMI Driver
29
JDBC Driver: Type 3 (Java Protocol)
Disadvantages
• Compared to Type 2 drivers, Type 3 drivers are
slow due to increased number of network calls.
• Requires database-specific coding to be done in
the middle tier.
• The middleware layer added may result in
additional latency, but is typically overcome by
using better middleware services.
30
JDBC Driver: Type 4 (Database Protocol)
• It is known as the Direct to Database Pure Java Driver
• Need to download a new driver for each database engine
e.g. Oracle, MySQL
• Type 4 driver, a pure Java-based driver communicates
directly with the vendor's database through socket
connection.
• This kind of driver is extremely flexible, you don't need to
install special software on the client or server.
• Such drivers are implemented by DBMS vendors.
31
JDBC Driver: Type 4 (Database Protocol)
Local Computer
Java Application
Application Code
Type 4
100% Pure Java Local
DBMS
Database Server
32
33
JDBC Driver: Type 4 (Database Protocol)
Advantages
• Completely implemented in Java to achieve platform independence.
• No native libraries are required to be installed in client machine.
• These drivers don't translate the requests into an intermediary format
(such as ODBC).
• Secure to use since, it uses database server specific protocol.
• The client application connects directly to the database server.
• No translation or middleware layers are used, improving performance.
• The JVM manages all the aspects of the application-to-database
connection.
Disadvantage
• This Driver uses database specific protocol and it is DBMS vendor
dependent.
34
JDBC Driver
Thin Driver You can connect to a database without the client installed on your
machine. E.g. Type 4.
Thick Driver Thick client would need the client installation.
E.g. Type 1 and Type 2.
35
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Name: JDBC-ODBC Native Code Java Protocol/ Database Protocol
Bridge Driver/ JNI Middleware
Vendor No Yes No Yes
Specific:
Portable No No Yes Yes
37
Which Driver should be Used?
• If you are accessing one type of database such as
MySql, Oracle, Sybase or IBM etc., the preferred
driver type is 4.
• If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
• Type 2 drivers are useful in situations, where a type 3
or type 4 driver is not available yet for your database.
• The type 1 driver is not considered a
deployment-level driver, and is typically used for
development and testing purposes only.
38
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName
39
GTU Question : JDBC
1 What is JDBC? List out all various types of JDBC Driver. Explain Sum’16
Thick and Thin driver. Write code snippet for each type of JDBC
connection. Comment on selection of driver. [7 Marks]
2 What is JDBC? Explain the types of JDBC drivers? Write a code Win’16
snippet for each type of JDBC connection. [7 Marks]
3 Explain JDBC driver types in detail. [7 Marks] Sum’17
40
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
41
JDBC Components
The JDBC API provides the following interfaces and classes
Package java.sql
Class
43
JDBC Package
java.sql
44
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
45
JDBC Process
Step 1: Loading JDBC Driver
Step 2: Connection to DBMS
Step 3: Creating and executing statement
Step 4: Processing data returned by the DBMS
Step 5: Terminating Connection with DBMS
46
Step 1: Loading JDBC Driver
• Create an instance of the driver
• Register driver in the driver manager
• Loading the driver or drivers
for example, you want to use driver for mysql, the
following code will load it:
Returns the Class object associated with the
class or interface with the given string name.
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection(URL,USER_NM,PASS);
Example:
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu","root", "pwd");
Database Name
49
Step 3: Creating statement
• Once a connection is obtained, we can interact with the
database.
• The JDBC Statement interfaces define the methods and
properties that enable you to send SQL or PL/SQL
commands and receive data from your database.
Statement st=con.createStatement();
50
Step 3:Executing Statement
• Once you've created a Statement object, you can
then use it to execute an SQL statement with one
of its three execute methods.
ResultSet executeQuery(String Returns a ResultSet object. Use this method
sql) throws SQLException when you expect to get a result set, as you
would with a SELECT statement.
51
Step 3: Executing Statement
Syntax:
ResultSet rs=st.executeQuery(“query”);
Example
ResultSet rs = stmt.executeQuery
("SELECT * from student");
52
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * from student");
ResultSet rs
Enr_no Name Branch
601 abc ce
602 pqr me
Database
603 rst ec
604 def Ci
53
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * FROM student WHERE
Enr_no='601'OR Enr_no='602'");
ResultSet rs
Enr_no Name Branch
Database
601 abc ce
602 pqr me
54
Step 4:Processing data returned by the DBMS
• Method: Resultset
boolean next() Moves the cursor forward one row from its
Throws SQLException current position.
String getString Retrieves the value of the designated column in
(int col_Index) the current row of this ResultSet object as
throws SQLException a String
String getString Retrieves the value of the designated column in
(String col_Label) the current row of this ResultSet object as
throws SQLException a String in the Java programming language.
int getInt Returns the int in the current row in the
(int columnIndex) throws specified column index.
SQLException
int getInt Retrieves the value of the designated column in
(String columnLabel) the current row
throws SQLException
55
Processing data returned by the DBMS
• Example
while(rs.next()) Returns the value of
specified Column number
{
System.out.println(rs.getString(1));
System.out.println(rs.getInt(“emp_id”)
);
} Returns the value of specified Column name
56
Step 5:Terminating Connection with DBMS
• The connection of DBMS is terminated by using
close() method.
Example
Releases this ResultSet object's
rs.close(); database and JDBC resources
immediately
st.close();
Releases this Statement object's
database and JDBC resources
con.close(); immediately
57
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName
58
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
59
JDBC Program
Class.forName("com.mysql.jdbc.Driver");
Connection conn=
DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu",
“root”, “pwd”);
ResultSet rs = stmt.executeQuery("SELECT
* from student");
while(rs.next())
System.out.print(rs.getString(1));
stmt.close();
conn.close();
60
First JDBC Program
1. import java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver"); Database name
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu","root",”pwd");
8. Statement stmt = conn.createStatement();
9. ResultSet rs = stmt.executeQuery("SELECT * from student");
10. while(rs.next()){
11. System.out.print(rs.getInt(1)+"\t");
Table name
12. System.out.print(rs.getString(“Name”)+"\t");
13. System.out.println(rs.getString(3));
14. }//while
15. stmt.close();
16. conn.close();
17. }catch(Exception e){System.out.println(e.toString());
18. }//PSVM }//class
61
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
62
Types of Statement
• The JDBC Statement, PreparedStatement and
CallableStatement interface define the methods
and properties that enable you to send SQL or PL/SQL
commands and receive data from your database.
java.sql interface
Use the for general-purpose access to
your database.
Useful for static SQL statements.
Statement Cannot accept parameters.
Table Name
Parameter 2
64
Methods of PreparedStatement interface
public void Sets the integer value to the given parameter
setInt(int paramIndex, int value) index.
public void Sets the String value to the given parameter
setString(int paramIndex, String value) index.
public int executeUpdate() Executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() Executes the select query. It returns an instance
of ResultSet.
65
Prepared Statement
• Now to create table in mysql.
create table gtu.student2
(
Enr_no VARCHAR(10) not null
Name VARCHAR(20),
Branch VARCHAR(10),
Division VARCHAR(10),
primary key (Enr_no)
)
66
Example of PreparedStatement that inserts the record
1. import java.sql.*;
2. public class PreparedInsert {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
8. String query="insert into student2 values(?,?,?,?)";
9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, "14092"); //Enr_no
11. ps.setString(2, "abc_comp"); //Name
12. ps.setString(3, "computer"); //Branch
13. ps.setString(4, "cx"); //Division
14. int i=ps.executeUpdate();
15. System.out.println("no. of rows updated ="+i);
16. ps.close();
17. conn.close();
18. }catch(Exception e){System.out.println(e.toString());} }//PSVM
}//class
67
Why to use PreparedStatement?
Improves performance:
• The performance of the application will be faster, if you
use PreparedStatement interface because query is
compiled only once.
• This is because creating a PreparedStatement object by
explicitly giving the SQL statement causes the statement
to be precompiled within the database immediately.
• Thus, when the PreparedStatement is later executed, the
DBMS does not have to recompile the SQL statement.
• Late binding and compilation is done by DBMS.
• Provides the programmatic approach to set the values.
68
GTU Exam Question
1. Show the use of PreparedStatement object to run Sum’16
precompiled SQL statement. Also write example of
java snippet for PreparedStaement.[7]
2. Explain the use of PreparedStatement with Win’16
appropriate example.[7]
3. Explain role of Prepared Statement with example.[7] Sum’17
4. Write a program to insert student records to Win’17
database using prepared statement.[7]
69
Callable Statement
• CallableStatement interface is used to call
the stored procedures.
• We can have business logic on the database by
the use of stored procedures that will make the
performance better as they are precompiled.
Example
Suppose you need the get the age an employee
based on the date of birth, you may create a
procedure that receives date as the input and
returns age of the employee as the output.
70
Callable Statement
• Three types of parameters exist: IN, OUT, and
INOUT. The PreparedStatement object only uses the
IN parameter. The CallableStatement object can use
all the three.
Parameter Description
IN A parameter whose value is unknown when the SQL statement is
created. You bind values to IN parameters with the setXXX()
methods.
INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.
71
Callable Statement
• Create mysql procedure to get book title for given
ISBN number.
Table: book
DB Column Name
DB Column Name
72
Example CallableStatement
1. import java.sql.*;
2. public class CallableDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
13. cs.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class
73
GTU Exam Question
1. Explain role of Callable Statement with example[7] Sum’17
2. Discuss CallableStatement with example.[4] Win’17
74
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
75
Method: ResultSet
Categories
1. Navigational methods Used to move the cursor around.
2. Get methods Used to view the data in the columns of the current row
3. Update methods Used to update the data in the columns of the current
database as well.
76
ResultSet: Navigational methods
boolean first() Moves the cursor to the first row.
throws SQLException
boolean last() Moves the cursor to the last row.
throws SQLException
boolean next() Moves the cursor to the next row. This method
throws SQL Exception returns false if there are no more rows in the result
set.
boolean previous() Moves the cursor to the previous row. This method
throws SQLException returns false if the previous row is off the result set.
boolean absolute(int row) throws Moves the cursor to the specified row.
SQLException
boolean relative(int row) throws Moves the cursor the given number of rows forward
SQLException or backward, from where it is currently pointing.
int getRow() Returns the row number that the cursor is pointing to.
throws SQLException
77
ResultSet: Get methods
int getInt(String columnName) Returns the int in the current row in the column
throws SQLException named columnName.
int getInt(int columnIndex) throws Returns the int in the current row in the specified
SQLException column index. The column index starts at 1,
meaning the first column of a row is 1, the second
column of a row is 2, and so on.
78
ResultSet: Update methods
void updateString(int col_Index, String s) Changes the String in the specified column to
throws SQLException the value of s.
79
Types of ResultSet
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the
result set. Default
Type
80
Concurrency of ResultSet
Concurrency Description
ResultSet.CONCUR_READ_ONL Creates a read-only result set. Default
Type
Y
ResultSet.CONCUR_UPDATABL Creates an updateable result set.
E
81
ResultSet
try {
Statement stmt =
conn.createStatement( ResultSet Type
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
.... ResultSet Concurrency
82
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
83
ResultSetMetaData Interface
• The metadata means data about data.
• If you have to get metadata of a table like
i. total number of column
ii. column name
iii. column type etc.
• ResultSetMetaData interface is useful because it
provides methods to get metadata from the
ResultSet object.
84
Method: ResultSetMetaData
int getColumnCount() it returns the total number of columns in the
throws SQLException ResultSet object.
String getColumnName(int index) it returns the column name of the specified column
throws SQLException index.
String getColumnTypeName(int it returns the column type name for the specified
index) index.
throws SQLException
85
ResultSetMetaData
1. import java.sql.*;
2. public class MetadataDemo {
3. public static void main(String[] args) {
4. try {Class.forName("com.mysql.jdbc.Driver");
5. Connection conn= DriverManager.getConnection
6. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
7. Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from student");
9. ResultSetMetaData rsmd=rs.getMetaData();
10. System.out.println("Total columns: "+rsmd.getColumnCount());
11. System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
12. System.out.println("Column Type Name of 1st column:“
+rsmd.getColumnTypeName(1));
13. stmt.close();
14. conn.close();
15. }catch(Exception e)
16. {System.out.println(e.toString());}
17. }//PSVM
18. }//class
86
DatabaseMetadata
• DatabaseMetaData interface provides methods
to get meta data of a database such as
87
DatabaseMetadata
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/temp6","root","root");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("getDatabaseProductName:“
+dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():“
+dbmd.getDatabaseProductVersion());
System.out.println("getDriverName():"+dbmd.getDriverName());
System.out.println("getDriverVersion():“
+dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());
88
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
89
Executing SQL updates
1. import java.sql.*;
2. class UpdateDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. Statement stmt=con.createStatement();
8. String query="update student set Name='abc601' where
Enr_no=601";
9. int i=stmt.executeUpdate(query);
10. System.out.println("total no. of rows updated="+i);
11. stmt.close();
12. con.close();
13. }catch(Exception e){ System.out.println(e);}
14. } }
90
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
91
Transaction Management
Transaction Succeed
it
m m
Co
Transaction
Initial State
Ro
llba
ck
Transaction Failed
92
Transaction Management
• In JDBC, Connection interface provides methods
to manage transaction.
void setAutoCommit(boolean status) It is true by default, means each
transaction is committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
93
Transaction Management:commit
1. import java.sql.*;
2. class CommitDemo{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/GTU","root","root");
8. con.setAutoCommit(false);//bydefault it is true
9. Statement stmt=con.createStatement();
10. int i=stmt.executeUpdate("insert into student
values(605,'def','ci')");
11. System.out.println("no. of rows inserted="+i);
12. con.commit();//commit transaction
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }}
94
Transaction Management:rollback
1. import java.sql.*;
2. class RollbackDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into student
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into student values(607,'mno','ch')");
12. System.out.println("no. of rows inserted="+i);
13. con.rollback(); //Rollback Transaction
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }}
95
Transaction Isolation Level
• JDBC isolation level represents that, how a
database maintains its interiority against the
problem such as
1. dirty reads
2. non-repeatable reads
3. phantom reads
that occurs during concurrent transactions.
96
Transaction Isolation Level
What is Dirty read?
• Dirty read occurs when one transaction is changing the record,
and the other transaction can read this record before the first
transaction has been committed or rolled back.
• This is known as a dirty read scenario because there is always a
possibility that the first transaction may rollback the change,
resulting in the second transaction having read an invalid data.
97
Transaction Isolation Level
What is Non-Repeatable Read?
• Non Repeatable Reads happen when in a same
transaction same query yields to a different
result.
• This occurs when one transaction repeatedly
retrieves the data, while a difference transactions
alters the underlying data.
• This causes the different or non-repeatable
results to be read by the first transaction.
98
Transaction Isolation Level
What is Phantom read?
• At the time of execution of a transaction, if two
queries that are identical are executed, and the
rows returned are different from other.
• If you execute a query at time T1 and re-execute
it at time T2, additional rows may have been
added to the database, which may affect your
results.
• It is stated that a phantom read occurred.
99
Phantom reads vs Non-repeatable reads
Variable
Undefined
Same query had
retrieved two
different value
100
Transaction Isolation Level
Int Val. Isolation Level Description
1 TRANSACTION_READ_UNCOMMITTED It allows non-repeatable reads, dirty
reads and phantom reads to occur
2 TRANSACTION_READ_COMMITTED It ensures only those data can be read
which is committed. Prevents dirty
reads.
4 TRANSACTION_REPEATABLE_READ It is closer to serializable, but phantom
reads are also possible.
Prevents dirty and non-repeatable
reads.
8 TRANSACTION_SERIALIZABLE In this level of isolation dirty reads,
non-repeatable reads, and phantom
reads are prevented.
101
Transaction Isolation Level:program
IsolationDemo.java
public class IsolationDemo {
public static void main(String[] args) throws
ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306 /ce17","root",
“rngpit");
System.out.println("getTransactionIsolation=" +
con.getTransactionIsolation());
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
System.out.println("NEW getTransactionIsolation=" +
con.getTransactionIsolation());
}
}
102
SQL Exception
java.sql.SQLException It is a core JDBC exception class that provides
information about database access errors and other
errors. Most of the JDBC methods throw SQLException.
java.sql. It provides the update counts for all commands that
BatchUpdateException were executed successfully during the batch update.
103
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC
104
Batch Processing in JDBC
• Instead of executing a single query, we can
execute a batch (group) of queries.
• It makes the performance fast.
• The java.sql.Statement and
java.sql.PreparedStatement interfaces provide
methods for batch processing.
Methods of Statement interface
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.
105
Batch Processing in JDBC
1. Class.forName("com.mysql.jdbc.Driver");
2. Connection con=DriverManager.getConnection(
3. "jdbc:mysql://localhost:3306/GTU","root","root");
4. con.setAutoCommit(false);
5. Statement stmt=con.createStatement();
Create table
6. String query1,query2,query3,query4,query5;
7. query1="create table student(enr INT PRIMARY KEY, name VARCHAR(20),sem
INT,branch VARCHAR(10))";
8. query2="insert into student values(6001,'java',6,'ce')"; Insert
record
9. query3="insert into student values(6002,'php',6,'ce')";
10. query4="update student set name='cg' where enr=6002";
Update record
11. query5="delete from student where name='java'";
12. stmt.addBatch(query1);
13. stmt.addBatch(query2); Delete record
14. stmt.addBatch(query3);
15. stmt.addBatch(query4);
16. stmt.addBatch(query5);
17. int[] i=stmt.executeBatch();
18. con.commit();
106
GTU Questions:
1. What is JDBC? [Win -14]
List out different types of JDBC driver and explain role of each. [Sum -15]
Write code snippet for each type of JDBC connection. [Win -15]
Explain Thick and Thin driver. [Sum -16]
Comment on selection of driver. [Win -16]
2. Explain Prepared statements with suitable example [Win -15]
[Sum -16]
[Win -16]
[Win -17]
3. Give the use of Statement, PreparedStatement and CallableStatement [Win -14]
object. Write code to insert three records into student table using
PreparedStatement (assume student table with Name, RollNo, and Branch
field).
4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16]
5. Discuss CallableStatement with example. [Win -17]
107
JDBC Interview Question
1. What is the difference between execute, executeQuery, executeUpdate?
2. What are the benefits of PreparedStatement over Statement?
3. What is JDBC Savepoint? How to use it?
4. What is JDBC Connection isolation levels?
5. What is CLOB and BLOB datatypes in JDBC?
6. What is difference between java.util.Date and java.sql.Date?
7. What is SQL Warning? How to retrieve SQL warnings in the JDBC program?
8. Which type of JDBC driver is the fastest one?
9. What does Class.forName return?
10. What happens if we call resultSet.getInt(0).
108