SlideShare a Scribd company logo
Java Database Connectivity
Chapter 6: JDBC Objects
EduBridgeIndia Pvt.Ltd 1
EduBridgeIndia Pvt.Ltd 2
The Concept of JDBC
• Many industrial-strength DBMS available in the market
– Oracle, DB2, Sybase, MySQL
• Each DBMS defines its own low-level way to interact
with programs to access data stored in its databases
• JDBC driver is a translator that converts low level
proprietary DBMS messages to low-level messages
understood by the JDBC API, and vice versa
• Thus JDBC drivers and the JDBC API allow Java
developers to write high level code that accesses
any DBMS
JDBC: Java Database Connectivity
• JDBC is a standard Java API for handling
database related activities
• Note: The JDBC driver for different database is
different. But, as an end-user, we don’t have
to bother about their implementation.
3
EduBridgeIndia Pvt.Ltd
JDBC Architecture
EduBridgeIndia Pvt.Ltd 4
JDBC Driver Types – Type 1
• Type 1 JDBC/ODBC Bridge
– uses bridge technology to connect a Java client to
a third-party API such as Open DataBase
Connectivity (ODBC)
– eg - Sun's JDBC-ODBC bridge
EduBridgeIndia Pvt.Ltd 5
JDBC Driver Types – Type 2
• Type 2 Java/Native Code Driver
– This type of driver wraps a native API with Java
classes
– eg : Oracle Call Interface (OCI) driver
EduBridgeIndia Pvt.Ltd
6
JDBC Driver Types – Type 3
• Type 3 JDBC Driver
– This type of driver communicates using a network
protocol to a middle tier server
– middle tier in turn communicates to the database
EduBridgeIndia Pvt.Ltd 7
JDBC Driver Types – Type 4
• Type 4 JDBC Driver
– These convert JDBC requests to database-specific
network protocols, so that Java programs can
connect directly to a database
– written entirely in Java
EduBridgeIndia Pvt.Ltd 8
EduBridgeIndia Pvt.Ltd 9
JDBC Packages
• Two packages named java.sql and javax.sql
– Java.sql
• contains core data objects of JDBC API
• Provides basics for connecting to the DBMS and
interacting with data stored in the DBMS
– Javax.sql :
• Extends java.sql
• contains Java data objects that interact with Java
Naming and Directory Interface (JNDI) and that manage
connection pooling, etc.
EduBridgeIndia Pvt.Ltd 10
Brief Overview of the JDBC process
• Process divided into five routines
– Load the driver
– Connect to the DBMS
– Create and Execute a Statement object
– Process data returned by the DBMS
– Terminate the connection with the DBMS
EduBridgeIndia Pvt.Ltd 11
Steps to use JDBC in Java Program
Phase Task Relevant java.sql classes
Initialisation Load Driver
Create connection
DriverManager
Connection
Processing Generate SQL statements
Process result data
Statement
ResultSet
Termination Terminate connection
Release data structures
Connection
Statement
EduBridgeIndia Pvt.Ltd 12
Loading the JDBC driver
• JDBC drivers must be loaded before the Java
application connects to the DBMS
• The Class.forName() is used to load the JDBC
driver
Class.forName("com.mysql.cj.jdbc.Driver");
EduBridgeIndia Pvt.Ltd 13
Connect to the DBMS
• Use DriverManager.getConnection() method
– DriverManager is highest class in Java.sql
hierarchy; responsible for managing driver related
information
– method is passed the URL of the database and
user ID and password required by the
database
– URL is the string object that contains the driver
name that is being accessed
– method returns Connection interface that is used
throughout the process to reference the
database
EduBridgeIndia Pvt.Ltd 14
Connect to the DBMS
• Parameters of DriverManager.getConnection()
method
– (String url, String userID, String password);
<protocol>:<subprotocol>:<dsn-
– URL format :
name>
• Conncetion con =
DriverManager.getConnection(“jdbc:odbc:cus
tomer”, “root”, “root”);
• Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost/TEST","root",
"password");
EduBridgeIndia Pvt.Ltd 15
Create Statement object
• Create Statement object which will be used
to execute the query
Statement
stmt=con.createStatement();
EduBridgeIndia Pvt.Ltd 16
Execute the query
• Execute and process the query which returns the
ResultSet object
• ResultSet object is assigned the results received
from the DBMS after the query is processed
ResultSet rs =
stmt.executeQuery("select * from
Employees");
• Employees is the table name
EduBridgeIndia Pvt.Ltd 17
Process the results - 1
• next() method of ResultSet is used to
iterate throughout the result set
while(rs.next())
{ System.out.printl
n(
rs.getInt(1)+" "+
rs.getString(2) )+" "+
rs.getString(3)+" "+
rs.getString(4));
}
EduBridgeIndia Pvt.Ltd 18
Process the results - 2
• ResultSet also contains several getXxx( ) methods to read the value
from particular column of current row
• Eg - getString(“name”) will read the value from column ‘name’ in
the form of string
String name;
int age;
do
{
name = rs.getString(“name”);
age = rs.getInt(“age”);
System.out.println(name+“--”+age);
} while(rs.next());
EduBridgeIndia Pvt.Ltd 19
Terminate the Connection
• Use close() method of Connection object once
Java program has finished accessing the DBMS
• Method throws as exception if problem is
encountered
con.close();
EduBridgeIndia Pvt.Ltd 20
Exception Handling- 1
• Class.forName() method throws a
ClassNotFoundException if an error occurs while
loading the JDBC driver
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.err.println(“Unable to load the driver” + e);
System.exit(1);
}
EduBridgeIndia Pvt.Ltd 21
Exception Handling - 2
• DriverManager.getConnection() method throws a
SQLException if the driver rejects access to the DBMS
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost/
TEST","root","password");
} catch(ClassNotFoundException e)
{ System.err.println(“Unable to load the driver”+
e); System.exit(1);
} catch(SQLException e) {
System.err.println(“Cannot connect to the database”+
e);
System.exit(1);
}
Complete Program
import java.sql.*;
class JDBCDemo{
public static void main(String args[]){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysq
l://localhost/TEST",
"root","password");
//here TEST is the database name,
//root is the username and root is the
password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Employees");
while(rs.next())
System.out.println(rs.getInt(1)+"
"+rs.getString(2)
+"
"+rs.getString(3)+rs.getString(4));
con.close();
}catch(Exception e) { System.out.println(e);}
}
} 22
EduBridgeIndia vt.Ltd
22
EduBridgeIndia Pvt.Ltd 23
Statement objects
• Once the connection to the database is opened,
Java application creates and sends a query to
access data contained in the database.
• Three type of statement objects:
– Statement Object: Executes a query immediately
– PreparedStatement Object: Executes a compiled
query
– CallableStatement Object: Executes a
stored
procedure
EduBridgeIndia Pvt.Ltd 24
The Statement Object - 1
• Statement object is used whenever a Java program needs
to immediately execute a query without first having query
compiled
• Three different methods available
1. executeQuery()
– This method returns the ResultSet object that contains rows,
columns and metadata that represent data requested by the
query.
– Generally, this method is used to execute only the ‘SELECT’
query of SQL
– Method Signature:
ResultSet executeQuery(String query);
EduBridgeIndia Pvt.Ltd 25
The Statement Object - 2
2. executeUpdate()
– This method is used to execute the queries that
contain INSERT, DELETE and UPDATE
statements
– Method returns integer indicating the number of
rows that were updated by the query
– Signature: int executeUpdate(String
query);
For example:
int rows = st.executeUpdate("DELETE
FROM EMPLOYEES WHERE STATUS=0");
EduBridgeIndia Pvt.Ltd 26
The Statement Object - 3
3. execute()
– This method is used to execute SQL statement which may return
multiple results
– Signature :
public boolean execute(String sql)
For example:
if(st.execute()) rs = st.getResultSet();
– Signatures of other methods:
• public ResultSet getResultSet()
• public int getUpdateCount()
• public boolean getMoreResults()
EduBridgeIndia Pvt.Ltd 27
PreparedStatement object -1
• SQL query must be compiled before the DBMS
processes it
• Compiling done after Statement object’s
execution method is called
• Compiling a query is an overhead that is
acceptable if the query is called once
• Compiling can become an expensive overhead
if the query is executed several times by the
same program during the same session
EduBridgeIndia Pvt.Ltd 28
PreparedStatement object -2
• PreparedStatement object can be used to precompile and
execute SQL query
• Query is created similar to other queries
• However, a question mark is given on the place for the
value that is inserted into the query after it is compiled
• It is the value that changes each time the query
is executed
• For example
“select * from nation where population
> ?”
EduBridgeIndia Pvt.Ltd 29
PreparedStatement object -3
• This type of the query is passed as the parameter to
the prepareStatement( ) method of the Connection
object which then returns the PreparedStatement
object
• For example
“select * from nation where population > ?”
PreparedStatement ps = prepareStatement(query);
• Once the PreparedStatement object is obtained, the
setXxx( ) methods is used to replace question mark
with the value passed to setXxx() method
EduBridgeIndia Pvt.Ltd 30
execute( )
PreparedStatement object -4
• Each setXxx() method specifies the data type of value that is being
passed
• For example
ps.setInt(1, 100000);
– First parameter (int--identifies position of the question mark
placeholder )
– Second Parameter (value that replaces the question mark)
• Next, use appropriate execute method depending upon type of the
query without any parameters
ResultSet rs = ps.executeQuery();
• This will generate the ResultSet object as the execution of the query
• PreparedStatement contains all three execute methods but without any
parameters
ResultSet executeQuery( ) int executeUpdate( ); boolean
30
PreparedStatement object -5
• The setXxx( ) methods:
void setBoolean(int index, boolean value);
void setByte(int index, byte value);
void setDate(int index, Date value);
void setDouble(int index, double value);
void setFloat(int index, float value);
void setInt(int index, int value);
void setLong(int index, long value);
void setObject(int index, Object value);
void setShort(int index, short value);
void setString(int index, String value);
Rakhi Saxena (Internet Technologies) 31
EduBridgeIndia Pvt.Ltd 31
Example: Prepared Statement
import java.sql.*;
class JDBCPreparedStatement{
public static void main(String args[])
{ try{ Class.forName("com.mysql.cj.jdbc.Dri
ver");
Connection
con=DriverManager.getConnection(
"jdbc:mysql://localhost/TEST","root","password");
PreparedStatement ps = con.prepareStatement("select * from
Employees where Age > ?");
ps.setInt(1,18); //set question marks place holder
ResultSet rs = ps.executeQuery(); //execute
System.out.println("Employees having age > 5 are:");
while(rs.next()) {
System.out.println(rs.get
Int(1)+" "+
rs.getString(2)+" "+
rs.getString(3)+"
"+ rs.getString(4));
}
} Rakhi Saxena (Internet Technologies) 32
EduBridgeIndia Pvt.Ltd 32
EduBridgeIndia Pvt.Ltd 33
CallableStatement Object
• CallableStatement - used to call stored procedures
from JDBC application program
• Stored procedure - block of code identified by a unique
name (can be written in PL/SQL, Transact-SQL, C, etc)
• CallableStatement object uses three types of parameters
when calling a stored procedure
– IN, OUT, INOUT
– IN parameter contains the data that needs to be passed to
the
stored procedure whose value is assigned using setXxx()
method
– OUT parameter contains the value returned by the stored
procedure, if any
– INOUT parameter is a single parameter that is used to both
pass
information and retrieve information from a stored procedure
EduBridgeIndia Pvt.Ltd 34
ResultSet
• SQL statements that read data from a database query,
return the data in a result set
• ResultSet object maintains a cursor (virtual pointer)
that points to the current row in the result set
• Initially, cursor points to before the first row
• next() method used to move the cursor to the one row
next from the current position
– Returns true if row contains data, false otherwise
– getXxx() method used to copy data from the row to a
collection, object, or variable
– Columns appear in the ResultSet in the order in which
column names appear in the SELECT statement
in the query
EduBridgeIndia Pvt.Ltd 35
Scrollable ResultSet
• Three ResultSet types:
• TYPE_FORWARD_ONLY (default type )
– ResultSet can only be navigated forward, move from row 1, to row 2, to row 3 etc
• TYPE_SCROLL_INSENSITIVE
– ResultSet can be navigated (scrolled) both forward and backwards
– Can also jump to a position relative to the current position, or jump to an absolute
position
– The ResultSet is insensitive to changes in the underlying data source
– if a record in the ResultSet is changed in the database by another thread or process, it
will not be reflected in already opened ResulsSet's of this type
• TYPE_SCROLL_SENSITIVE
– ResultSet can be navigated (scrolled) both forward and backwards
– can also jump to a position relative to the current position, or jump to an absolute
position
– The ResultSet is sensitive to changes in the underlying data source
– if a record in the ResultSet is changed in the database by another thread or process, it
will be reflected in already opened ResulsSet's of this type.
EduBridgeIndia Pvt.Ltd 36
Navigation Methods
METHOD DESCRIPTION
absolute() Moves the ResultSet to point at an absolute position. The position is a
row number passed as parameter to the absolute() method.
afterLast() Moves the ResultSet to point after the last row in the ResultSet.
beforeFirst() Moves the ResultSet to point before the first row in the ResultSet.
first() Moves the ResultSet to point at the first row in the ResultSet.
last() Moves the ResultSet to point at the last row in the ResultSet.
next() Moves the ResultSet to point at the next row in the ResultSet.
previous() Moves the ResultSet to point at the previous row in the ResultSet.
relative() Moves the ResultSet to point to a position relative to its current
position. The relative position is passed as a parameter to the relative
method, and can be both positive and negative.
EduBridgeIndia Pvt.Ltd 37
Other ResultSet interface methods
METHOD DESCRIPTION
getRow() Returns the row number of the current row - the row currently
pointed to by the ResultSet.
getType() Returns the ResultSet type.
isAfterLast() Returns true if the ResultSet points after the last row. False if not.
isBeforeFirst() Returns true if the ResultSet points before the first row. False if not.
isFirst() Returns true if the ResultSet points at the first row. False if not.
METHOD DESCRIPTION
refreshRow() Refreshes the column values of that row with the latest values from
the database.
NOTE: Not all JDBC Drivers are not Scrollable
EduBridgeIndia Pvt.Ltd 38
Updatable ResultSet
• ResultSet concurrency determines whether
the ResultSet can be updated, or only read
• Not all databases and JDBC drivers support that
the ResultSet is updated
• ResultSet can have one of two concurrency
levels
– CONCUR_READ_ONLY – means the ResultSet can only
be read
– CONCUR_UPDATABLE - means that the ResultSet can
be both read and updated
EduBridgeIndia Pvt.Ltd 39
Updating a ResultSet
• Can update the columns of each row in
the ResultSet by using updateXXX() methods
result.updateString ("name" , "Alex");
result.updateInt ("age" , 55);
result.updateRow();
• Can also update a column using column index
instead of column name
result.updateString (1, "Alex");
result.updateInt (2, 55);
result.updateRow();
• It is when updateRow() is called that the database
is updated with the values of the row.
– If this method is not called, values updated in
the ResultSet are never sent to the database
EduBridgeIndia Pvt.Ltd 40
Inserting Rows into a ResultSet
• If ResultSet is updatable it is also possible to insert
rows into it
result.moveToInsertRow();
result.updateString (1, "Alex");
result.updateInt (2, 55);
result.insertRow();
result.beforeFirst();
• The row pointed to after calling moveToInsertRow() is a
special row, a buffer, which can be used to build up the
row until all column values has been set on the row.
• Once the row is ready to be inserted into the ResultSet,
the insertRow() method is called
• Important to move the ResultSet to a valid position
after inserting the new row

More Related Content

PDF
1586279370_Bsc(P)-VI-InternetTechnologies-3.pdf
PPTX
Jdbc presentation
PDF
PPT
jdbc_presentation.ppt
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
PPT
JDBC Connecticity.ppt
PPTX
PDF
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
1586279370_Bsc(P)-VI-InternetTechnologies-3.pdf
Jdbc presentation
jdbc_presentation.ppt
Core Java Programming Language (JSE) : Chapter XIII - JDBC
JDBC Connecticity.ppt
Chapter 5 JDBC.pdf for stufent of computer andtudent It s

Similar to jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt (20)

PPTX
Jdbc Java Programming
PPTX
PPTX
Database Access With JDBC
PPTX
Jdbc ppt
PDF
Presentation for java data base connectivity
PPT
Jdbc day-1
PPTX
Java- JDBC- Mazenet Solution
PPTX
Java Database Connectivity by shreyash simu dbce.pptx
PPTX
Java Data Base Connectivity concepts.pptx
PPT
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
PPT
CS124-L9-JDBC.ppt Add more information to your upload
PPT
Jdbc sasidhar
PPTX
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PPT
Jdbc oracle
PPT
Jdbc (database in java)
PPTX
Database Programming Techniques
PPT
JDBC.ppt
Jdbc Java Programming
Database Access With JDBC
Jdbc ppt
Presentation for java data base connectivity
Jdbc day-1
Java- JDBC- Mazenet Solution
Java Database Connectivity by shreyash simu dbce.pptx
Java Data Base Connectivity concepts.pptx
JDBC JAVA DATABASE CONNECTIVITY AND JAVA
CS124-L9-JDBC.ppt Add more information to your upload
Jdbc sasidhar
Java OOP Programming language (Part 8) - Java Database JDBC
Jdbc oracle
Jdbc (database in java)
Database Programming Techniques
JDBC.ppt
Ad

More from Indu32 (12)

PDF
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
PPTX
Introduction to MySQL commands mysql presentation 22.pptx
PDF
unit8_jdbc.pdf mysql and java jdbc connection
PPTX
css front end development , designing web page
PPTX
CSS presentation for beginners where they can understand easily
PPTX
html webpage development different tags used
PPTX
design patter related ppt and presentation
PPTX
Web development ppt used to design web applocation
PPTX
In the given example only one object will be created. Firstly JVM will not fi...
PPT
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
PPT
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
PPT
java basic ppt introduction, The Java language is known for its robustness, s...
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
Introduction to MySQL commands mysql presentation 22.pptx
unit8_jdbc.pdf mysql and java jdbc connection
css front end development , designing web page
CSS presentation for beginners where they can understand easily
html webpage development different tags used
design patter related ppt and presentation
Web development ppt used to design web applocation
In the given example only one object will be created. Firstly JVM will not fi...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
java basic ppt introduction, The Java language is known for its robustness, s...
Ad

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Pre independence Education in Inndia.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Structure & Organelles in detailed.
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
01-Introduction-to-Information-Management.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Microbial diseases, their pathogenesis and prophylaxis
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O7-L3 Supply Chain Operations - ICLT Program
Pre independence Education in Inndia.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Basic Mud Logging Guide for educational purpose
Final Presentation General Medicine 03-08-2024.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Structure & Organelles in detailed.
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
01-Introduction-to-Information-Management.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Anesthesia in Laparoscopic Surgery in India
Renaissance Architecture: A Journey from Faith to Humanism
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Types and Its function , kingdom of life
2.FourierTransform-ShortQuestionswithAnswers.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student

jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt

  • 1. Java Database Connectivity Chapter 6: JDBC Objects EduBridgeIndia Pvt.Ltd 1
  • 2. EduBridgeIndia Pvt.Ltd 2 The Concept of JDBC • Many industrial-strength DBMS available in the market – Oracle, DB2, Sybase, MySQL • Each DBMS defines its own low-level way to interact with programs to access data stored in its databases • JDBC driver is a translator that converts low level proprietary DBMS messages to low-level messages understood by the JDBC API, and vice versa • Thus JDBC drivers and the JDBC API allow Java developers to write high level code that accesses any DBMS
  • 3. JDBC: Java Database Connectivity • JDBC is a standard Java API for handling database related activities • Note: The JDBC driver for different database is different. But, as an end-user, we don’t have to bother about their implementation. 3 EduBridgeIndia Pvt.Ltd
  • 5. JDBC Driver Types – Type 1 • Type 1 JDBC/ODBC Bridge – uses bridge technology to connect a Java client to a third-party API such as Open DataBase Connectivity (ODBC) – eg - Sun's JDBC-ODBC bridge EduBridgeIndia Pvt.Ltd 5
  • 6. JDBC Driver Types – Type 2 • Type 2 Java/Native Code Driver – This type of driver wraps a native API with Java classes – eg : Oracle Call Interface (OCI) driver EduBridgeIndia Pvt.Ltd 6
  • 7. JDBC Driver Types – Type 3 • Type 3 JDBC Driver – This type of driver communicates using a network protocol to a middle tier server – middle tier in turn communicates to the database EduBridgeIndia Pvt.Ltd 7
  • 8. JDBC Driver Types – Type 4 • Type 4 JDBC Driver – These convert JDBC requests to database-specific network protocols, so that Java programs can connect directly to a database – written entirely in Java EduBridgeIndia Pvt.Ltd 8
  • 9. EduBridgeIndia Pvt.Ltd 9 JDBC Packages • Two packages named java.sql and javax.sql – Java.sql • contains core data objects of JDBC API • Provides basics for connecting to the DBMS and interacting with data stored in the DBMS – Javax.sql : • Extends java.sql • contains Java data objects that interact with Java Naming and Directory Interface (JNDI) and that manage connection pooling, etc.
  • 10. EduBridgeIndia Pvt.Ltd 10 Brief Overview of the JDBC process • Process divided into five routines – Load the driver – Connect to the DBMS – Create and Execute a Statement object – Process data returned by the DBMS – Terminate the connection with the DBMS
  • 11. EduBridgeIndia Pvt.Ltd 11 Steps to use JDBC in Java Program Phase Task Relevant java.sql classes Initialisation Load Driver Create connection DriverManager Connection Processing Generate SQL statements Process result data Statement ResultSet Termination Terminate connection Release data structures Connection Statement
  • 12. EduBridgeIndia Pvt.Ltd 12 Loading the JDBC driver • JDBC drivers must be loaded before the Java application connects to the DBMS • The Class.forName() is used to load the JDBC driver Class.forName("com.mysql.cj.jdbc.Driver");
  • 13. EduBridgeIndia Pvt.Ltd 13 Connect to the DBMS • Use DriverManager.getConnection() method – DriverManager is highest class in Java.sql hierarchy; responsible for managing driver related information – method is passed the URL of the database and user ID and password required by the database – URL is the string object that contains the driver name that is being accessed – method returns Connection interface that is used throughout the process to reference the database
  • 14. EduBridgeIndia Pvt.Ltd 14 Connect to the DBMS • Parameters of DriverManager.getConnection() method – (String url, String userID, String password); <protocol>:<subprotocol>:<dsn- – URL format : name> • Conncetion con = DriverManager.getConnection(“jdbc:odbc:cus tomer”, “root”, “root”); • Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/TEST","root", "password");
  • 15. EduBridgeIndia Pvt.Ltd 15 Create Statement object • Create Statement object which will be used to execute the query Statement stmt=con.createStatement();
  • 16. EduBridgeIndia Pvt.Ltd 16 Execute the query • Execute and process the query which returns the ResultSet object • ResultSet object is assigned the results received from the DBMS after the query is processed ResultSet rs = stmt.executeQuery("select * from Employees"); • Employees is the table name
  • 17. EduBridgeIndia Pvt.Ltd 17 Process the results - 1 • next() method of ResultSet is used to iterate throughout the result set while(rs.next()) { System.out.printl n( rs.getInt(1)+" "+ rs.getString(2) )+" "+ rs.getString(3)+" "+ rs.getString(4)); }
  • 18. EduBridgeIndia Pvt.Ltd 18 Process the results - 2 • ResultSet also contains several getXxx( ) methods to read the value from particular column of current row • Eg - getString(“name”) will read the value from column ‘name’ in the form of string String name; int age; do { name = rs.getString(“name”); age = rs.getInt(“age”); System.out.println(name+“--”+age); } while(rs.next());
  • 19. EduBridgeIndia Pvt.Ltd 19 Terminate the Connection • Use close() method of Connection object once Java program has finished accessing the DBMS • Method throws as exception if problem is encountered con.close();
  • 20. EduBridgeIndia Pvt.Ltd 20 Exception Handling- 1 • Class.forName() method throws a ClassNotFoundException if an error occurs while loading the JDBC driver try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch(ClassNotFoundException e) { System.err.println(“Unable to load the driver” + e); System.exit(1); }
  • 21. EduBridgeIndia Pvt.Ltd 21 Exception Handling - 2 • DriverManager.getConnection() method throws a SQLException if the driver rejects access to the DBMS try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection ("jdbc:mysql://localhost/ TEST","root","password"); } catch(ClassNotFoundException e) { System.err.println(“Unable to load the driver”+ e); System.exit(1); } catch(SQLException e) { System.err.println(“Cannot connect to the database”+ e); System.exit(1); }
  • 22. Complete Program import java.sql.*; class JDBCDemo{ public static void main(String args[]){ try{ Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysq l://localhost/TEST", "root","password"); //here TEST is the database name, //root is the username and root is the password Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from Employees"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2) +" "+rs.getString(3)+rs.getString(4)); con.close(); }catch(Exception e) { System.out.println(e);} } } 22 EduBridgeIndia vt.Ltd 22
  • 23. EduBridgeIndia Pvt.Ltd 23 Statement objects • Once the connection to the database is opened, Java application creates and sends a query to access data contained in the database. • Three type of statement objects: – Statement Object: Executes a query immediately – PreparedStatement Object: Executes a compiled query – CallableStatement Object: Executes a stored procedure
  • 24. EduBridgeIndia Pvt.Ltd 24 The Statement Object - 1 • Statement object is used whenever a Java program needs to immediately execute a query without first having query compiled • Three different methods available 1. executeQuery() – This method returns the ResultSet object that contains rows, columns and metadata that represent data requested by the query. – Generally, this method is used to execute only the ‘SELECT’ query of SQL – Method Signature: ResultSet executeQuery(String query);
  • 25. EduBridgeIndia Pvt.Ltd 25 The Statement Object - 2 2. executeUpdate() – This method is used to execute the queries that contain INSERT, DELETE and UPDATE statements – Method returns integer indicating the number of rows that were updated by the query – Signature: int executeUpdate(String query); For example: int rows = st.executeUpdate("DELETE FROM EMPLOYEES WHERE STATUS=0");
  • 26. EduBridgeIndia Pvt.Ltd 26 The Statement Object - 3 3. execute() – This method is used to execute SQL statement which may return multiple results – Signature : public boolean execute(String sql) For example: if(st.execute()) rs = st.getResultSet(); – Signatures of other methods: • public ResultSet getResultSet() • public int getUpdateCount() • public boolean getMoreResults()
  • 27. EduBridgeIndia Pvt.Ltd 27 PreparedStatement object -1 • SQL query must be compiled before the DBMS processes it • Compiling done after Statement object’s execution method is called • Compiling a query is an overhead that is acceptable if the query is called once • Compiling can become an expensive overhead if the query is executed several times by the same program during the same session
  • 28. EduBridgeIndia Pvt.Ltd 28 PreparedStatement object -2 • PreparedStatement object can be used to precompile and execute SQL query • Query is created similar to other queries • However, a question mark is given on the place for the value that is inserted into the query after it is compiled • It is the value that changes each time the query is executed • For example “select * from nation where population > ?”
  • 29. EduBridgeIndia Pvt.Ltd 29 PreparedStatement object -3 • This type of the query is passed as the parameter to the prepareStatement( ) method of the Connection object which then returns the PreparedStatement object • For example “select * from nation where population > ?” PreparedStatement ps = prepareStatement(query); • Once the PreparedStatement object is obtained, the setXxx( ) methods is used to replace question mark with the value passed to setXxx() method
  • 30. EduBridgeIndia Pvt.Ltd 30 execute( ) PreparedStatement object -4 • Each setXxx() method specifies the data type of value that is being passed • For example ps.setInt(1, 100000); – First parameter (int--identifies position of the question mark placeholder ) – Second Parameter (value that replaces the question mark) • Next, use appropriate execute method depending upon type of the query without any parameters ResultSet rs = ps.executeQuery(); • This will generate the ResultSet object as the execution of the query • PreparedStatement contains all three execute methods but without any parameters ResultSet executeQuery( ) int executeUpdate( ); boolean 30
  • 31. PreparedStatement object -5 • The setXxx( ) methods: void setBoolean(int index, boolean value); void setByte(int index, byte value); void setDate(int index, Date value); void setDouble(int index, double value); void setFloat(int index, float value); void setInt(int index, int value); void setLong(int index, long value); void setObject(int index, Object value); void setShort(int index, short value); void setString(int index, String value); Rakhi Saxena (Internet Technologies) 31 EduBridgeIndia Pvt.Ltd 31
  • 32. Example: Prepared Statement import java.sql.*; class JDBCPreparedStatement{ public static void main(String args[]) { try{ Class.forName("com.mysql.cj.jdbc.Dri ver"); Connection con=DriverManager.getConnection( "jdbc:mysql://localhost/TEST","root","password"); PreparedStatement ps = con.prepareStatement("select * from Employees where Age > ?"); ps.setInt(1,18); //set question marks place holder ResultSet rs = ps.executeQuery(); //execute System.out.println("Employees having age > 5 are:"); while(rs.next()) { System.out.println(rs.get Int(1)+" "+ rs.getString(2)+" "+ rs.getString(3)+" "+ rs.getString(4)); } } Rakhi Saxena (Internet Technologies) 32 EduBridgeIndia Pvt.Ltd 32
  • 33. EduBridgeIndia Pvt.Ltd 33 CallableStatement Object • CallableStatement - used to call stored procedures from JDBC application program • Stored procedure - block of code identified by a unique name (can be written in PL/SQL, Transact-SQL, C, etc) • CallableStatement object uses three types of parameters when calling a stored procedure – IN, OUT, INOUT – IN parameter contains the data that needs to be passed to the stored procedure whose value is assigned using setXxx() method – OUT parameter contains the value returned by the stored procedure, if any – INOUT parameter is a single parameter that is used to both pass information and retrieve information from a stored procedure
  • 34. EduBridgeIndia Pvt.Ltd 34 ResultSet • SQL statements that read data from a database query, return the data in a result set • ResultSet object maintains a cursor (virtual pointer) that points to the current row in the result set • Initially, cursor points to before the first row • next() method used to move the cursor to the one row next from the current position – Returns true if row contains data, false otherwise – getXxx() method used to copy data from the row to a collection, object, or variable – Columns appear in the ResultSet in the order in which column names appear in the SELECT statement in the query
  • 35. EduBridgeIndia Pvt.Ltd 35 Scrollable ResultSet • Three ResultSet types: • TYPE_FORWARD_ONLY (default type ) – ResultSet can only be navigated forward, move from row 1, to row 2, to row 3 etc • TYPE_SCROLL_INSENSITIVE – ResultSet can be navigated (scrolled) both forward and backwards – Can also jump to a position relative to the current position, or jump to an absolute position – The ResultSet is insensitive to changes in the underlying data source – if a record in the ResultSet is changed in the database by another thread or process, it will not be reflected in already opened ResulsSet's of this type • TYPE_SCROLL_SENSITIVE – ResultSet can be navigated (scrolled) both forward and backwards – can also jump to a position relative to the current position, or jump to an absolute position – The ResultSet is sensitive to changes in the underlying data source – if a record in the ResultSet is changed in the database by another thread or process, it will be reflected in already opened ResulsSet's of this type.
  • 36. EduBridgeIndia Pvt.Ltd 36 Navigation Methods METHOD DESCRIPTION absolute() Moves the ResultSet to point at an absolute position. The position is a row number passed as parameter to the absolute() method. afterLast() Moves the ResultSet to point after the last row in the ResultSet. beforeFirst() Moves the ResultSet to point before the first row in the ResultSet. first() Moves the ResultSet to point at the first row in the ResultSet. last() Moves the ResultSet to point at the last row in the ResultSet. next() Moves the ResultSet to point at the next row in the ResultSet. previous() Moves the ResultSet to point at the previous row in the ResultSet. relative() Moves the ResultSet to point to a position relative to its current position. The relative position is passed as a parameter to the relative method, and can be both positive and negative.
  • 37. EduBridgeIndia Pvt.Ltd 37 Other ResultSet interface methods METHOD DESCRIPTION getRow() Returns the row number of the current row - the row currently pointed to by the ResultSet. getType() Returns the ResultSet type. isAfterLast() Returns true if the ResultSet points after the last row. False if not. isBeforeFirst() Returns true if the ResultSet points before the first row. False if not. isFirst() Returns true if the ResultSet points at the first row. False if not. METHOD DESCRIPTION refreshRow() Refreshes the column values of that row with the latest values from the database. NOTE: Not all JDBC Drivers are not Scrollable
  • 38. EduBridgeIndia Pvt.Ltd 38 Updatable ResultSet • ResultSet concurrency determines whether the ResultSet can be updated, or only read • Not all databases and JDBC drivers support that the ResultSet is updated • ResultSet can have one of two concurrency levels – CONCUR_READ_ONLY – means the ResultSet can only be read – CONCUR_UPDATABLE - means that the ResultSet can be both read and updated
  • 39. EduBridgeIndia Pvt.Ltd 39 Updating a ResultSet • Can update the columns of each row in the ResultSet by using updateXXX() methods result.updateString ("name" , "Alex"); result.updateInt ("age" , 55); result.updateRow(); • Can also update a column using column index instead of column name result.updateString (1, "Alex"); result.updateInt (2, 55); result.updateRow(); • It is when updateRow() is called that the database is updated with the values of the row. – If this method is not called, values updated in the ResultSet are never sent to the database
  • 40. EduBridgeIndia Pvt.Ltd 40 Inserting Rows into a ResultSet • If ResultSet is updatable it is also possible to insert rows into it result.moveToInsertRow(); result.updateString (1, "Alex"); result.updateInt (2, 55); result.insertRow(); result.beforeFirst(); • The row pointed to after calling moveToInsertRow() is a special row, a buffer, which can be used to build up the row until all column values has been set on the row. • Once the row is ready to be inserted into the ResultSet, the insertRow() method is called • Important to move the ResultSet to a valid position after inserting the new row