SlideShare a Scribd company logo
1
Java Database Connection (JDBC)
In 1996 Sun Microsystems came out with the JDBC
driver and the JDBC API.
The JDBC driver is really a specification that described
the detail functionality of a JDBC driver.
DBMS manufactures and third-party vendors were
encouraged to build JDBC drivers that conformed to
Sun's specifications.
2
Java Database Connection (JDBC)
Java programmers could then use high-level Java data
objects defined in the JDBC API to write a routine that
interacted with the DBMS.
Java data objects convert the routine into low-level
messages that conform to the JDBC driver specification
and send them to the JDBC driver.
The JDBC driver translates the routine into low-level
messages that are understood and processed by the
DBMS.
3
Java Database Connection (JDBC)
JDBC drivers created by DBMS manufactures have to perform:
• Open a connection between the DBMS and the J2EE
component.
• Translate low-level equivalents of SQL statements sent by the
J2EE component into messages that can be processed by the
DBMS.
• Return data that conforms to the JDBC specification to the
JDBC driver.
• Return information such as error messages that conforms to
the JDBC specification to the JDBC driver.
• Provide transaction management routines that conform to the
JDBC specification.
• Close the connection between the DBMS and the J2EE
component.
General Architecture
4
5
JDBC Driver Types
JDBC drivers are classified into four groups:
• Type 1 JDBC-to-ODBC Driver
• Type 2 Java/Native Code Driver
• Type 3 JDBC Driver
• Type 4 JDBC Driver
6
Type 1 JDBC-to-ODBC Driver

Database
Microsoft's Open Database Connection (ODBC) was used by
Sun Microsystems for the basis for creating JDBC.
Application Space
JDBC – ODBC Bridge
Database
SQL
Command
Result
Set
ODBC Driver
Proprietary
Protocol
Both ODBC and JDBC have similar driver
specifications and API. This driver type is sometimes
referred to as the JDBC/ODBC Bridge.
This driver is used to translate DBMS calls between the
JDBC specification and the ODBC specification.
 The JDBC-to-ODBC driver receives messages from a
J2EE component that conforms to the JDBC
specification talked about earlier.
Those messages are translated by the JDBC-to-ODBC
driver into the ODBC message format, which is then
translated into the message format understood by the
DBMS. 7
• Disadvantages
• This type driver should not be used in a mission-critical
application because the extra translation might
negatively impact performance.
• Since the Bridge driver is not written fully in Java, Type
1 drivers are not portable
 The client system requires the ODBC Installation to
use the driver.
 Not good for the Web.
8
9
Type 2 Java/Native Code Driver
This driver uses Java classes to generate platform-
specific code (code that is only understood by a specific
Java Application
Application Space
Type 2 JDBC Driver
Database
SQL
Command
Result
Set
Native
Database
Library
Proprietary
Protocol
 The manufacturer of the DBMS provides both the
Java/Native Code driver and API classes so the J2EE
component can generate the platform specific-code.
•Example: Oracle will have oracle native api.
•Advantage
•The distinctive characteristic of type 2 jdbc drivers are
that they are typically offer better performance than the
JDBC-ODBC Bridge as the layers of communication
(tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
10
• Disadvantage
• 1. Native API must be installed in the Client System
and hence type 2 drivers cannot be used for the
Internet.
2. Like Type 1 drivers, it’s not written in Java Language
which forms a portability issue.
3. If we change the Database we have to change the
native api as it is specific to a database
11
12
Type 3 JDBC Driver
All Java/Net-protocol driver
Application Space
Java Application
Type 3 JDBC Driver
Database
SQL
Command
Result
Set
Middleware
Component
Proprietary
Protocol
Server
• Translates JDBC calls into a database-independent
network protocol and sent to a middleware server.
• This server translates this DBMS-independent
protocol into a DBMS-specific protocol and sent to
the database
• Results sent back to the middleware and routed to
the client
13
Advantages
• 1. This driver is server-based, so there is no need for
any vendor database library to be present on client
machines.
2. This driver is fully written in Java and hence
Portable. It is suitable for the web.
3. There are many opportunities to optimize portability,
performance, and scalability.
4. The net protocol can be designed to make the client
JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for
features such as caching (connections, query results,
and so on), load balancing, and advanced
system administration such as logging and auditing.
14
• Disadvantage
• It requires another server application to install and
maintain. Traversing the recordset may take longer,
since the data comes through the backend server.
15
16
Type 4 JDBC Driver
Native-protocol/all-Java driver
Application Space
Java Application
Type 4 JDBC Driver
Database
SQL Command
Using Proprietary
Protocol
Result Set
Using Proprietary
Protocol
• This driver type is also known as the Type 4 database
protocol.
• It is similar to the Type 3 JDBC driver except SQL
queries are translated into the format required by the
DBMS.
• SQL queries do not need to be converted to JDBC-
formatted systems. This is the fastest way to
communicate SQL queries to the DBMS.
17
• Advantage
• 1. A type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence
2. Number of translation layers is very less i.e. type 4
JDBC drivers don’t have to translate database requests
to ODBC or a native connectivity interface or to pass
the request on to another server, performance is
typically quite good.
3. You don’t need to install special software on the
client or server. Further, these drivers can be
downloaded dynamically.
• Disadvantage
18
19
JDBC Packages
The JDBC API is contained in two packages.
• java.sql
• javax.sql
20
java.sql
This package contains core Java data objects of the JDBC
API. These include Java data objects that provide the
basis for connecting to the DBMS and interacting with
the data stored in the DBMS. java.sql is part of the J2SE.
To use this package in a Java application you must use the
following:
import java.sql.*;
21
javax.sql
This package contains the JDBC API. javax.sql extends
java.sql and is in the J2EE. Included in this package are
the Java data objects that interact with Java Naming and
Directory Interface (JNDI) and the Java data objects
that manage connection pooling, among other advanced
JDBC features.
To use this package in a Java application you must use the
following:
import javax.sql.*;
JDBC Concepts
• JDBC’s design is very similar to the design of
ODBC
• Driver Manager
• Loads database drivers, and manages the connection
between the application and the driver
• Driver
• Translates API calls into operations for a specific data
source
• Connection
• A session between an application and a database
JDBC Concepts (contd.)
• Statement
• An SQL Statement to perform a query or update
operation
• Metadata
• Information about returned data, the database
and the driver
• ResultSet
• Logical set of columns and rows returned by
executing an SQL statement (resulting tuples)
Steps Involved in Basic JDBC Operations
Driver
Driver Manager
Connection
Statement
Result Set
1. Load the JDBC driver class:
Class.forName(“driverName”);
2. Open a database connection:
DriverManager.getConnection
(“jdbc:xxx:datasource”);
3. Issue SQL statements:
stmt = con.createStatement();
stmt.executeQuery (“Select * from myTable”);
4. Process result set:
while (rs.next()) {
name = rs.getString(“name”);
amount = rs.getInt(“amt”); }
Database
25
A Brief Overview of the JDBC Process
1. Loading the JDBC driver
2. Connecting to the DBMS
3. Creating and executing a statement (like a SQL query)
4. Processing data returned by the DBMS (a result set)
5. Terminating the connection with the DBMS
26
Loading the JDBC driver
The JDBC driver must be loaded before the J2EE
component can connect to the DBMS.
 The Class.forName() method is used to load the
JDBC driver.
 For Ex.
27
Loading the JDBC driver - Example
import java.sql.*;
class Dboperation
{
public static void main(String args[]) {
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
}
catch ( ClassNotFoundException e ) {
System.out.println( "classname not found '" +
e.getMessage() + "'" );
System.exit( 0 );
}
catch (SQLException error) {
System.err.println("Cannot connect to the database." +
error);
System.exit( );
}}}
28
Connect to the DBMS
Once the driver is loaded, the J2EE component must
connect to the DBMS using the
The DriverManager.getConnection() method is
passed the URL of the database, and the user ID and
password if required by the DBMS.
The URL is a String object that contains the driver
name and the Data source name.
The DriverManager.getConnection() method returns
a Connection interface that is used throughout the
process to reference the database that is being accessed by
the J2EE component.
29
Connect to the DBMS Example
import java.sql.*;
class Dboperation
{
public static void main(String args[]) {
private String url = "jdbc:odbc:data source name";
private String userID = “ ";
private String password = “ ";
private static Connection Db;
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Db = DriverManager.getConnection( url, userID, password );}
catch ( ClassNotFoundException e ) {
System.out.println( "classname not found '" +
e.getMessage() + "'" );
System.exit( 0 );}
catch (SQLException error) {
System.err.println( "Cannot connect to the database." + error );
System.exit( );} }}
30
Create and Execute a SQL Statement
The Connect.createStatement() method is used to create a
Statement object.
The resulting Statement object is then used to execute a query and
return a Result Set object that contains the response from the
DBMS.
This response is usually one or more rows of information
requested by the J2EE component.
For ex. private Statement DataRequest;
DataRequest=Db.createStatement();
Typically, the query is assigned to a String object, which is passed
to the object's execute Query() method. Once the Result Set is
received from the DBMS, the close() method is called to terminate
the statement.
31
Create and Execute a SQL Statement - Example
import java.sql.*;
class Dboperation
{
public static void main(String args[]) {
private static Connection Db; // Connection object from above
private Statement Data Request; // create a Statement object
private Result Set Results; // create a ResultSet object
try {
// build SQL query in a String object
String query = "SELECT ... FROM table-name";
DataRequest = Db.createStatement();
Results = DataRequest.executeQuery( query );
}
catch ( SQLException error ){
System.err.println( "SQL error." + error );
System.exit( 3 );
}}}
32
Processing Data Returned by the DBMS
The java.sql.ResultSet object is assigned the results
received from the DBMS after the query is processed.
It also consists of methods used to interact with data
that is returned by the DBMS to the J2EE component.
Some of the methods used are the next(), getString(),
getxxx(), and close() methods.
33
next( ) method
Moves the cursor down one row from its current position. A
ResultSet cursor is initially positioned before the first row; the first
call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
34
close() method
Releases this ResultSet object's database and JDBC resources
immediately instead of waiting for this to happen when it is
automatically closed.
Note: A ResultSet object is automatically closed by the Statement
object that generated it when that Statement object is closed, re-
executed, or is used to retrieve the next result from a sequence of
multiple results. A ResultSet object is also automatically closed
35
Example
import java.sql.*;
private String LastName;
private boolean Records; // used for the next() method
.
.
try {
Records = Results.next();
if ( !Records ) {
System.out.println( "No data returned" );
System.exit( 4 );
}
}
catch ( SQLException error ) {
System.err.println( "SQL error." + error );
System.exit( 3 );
}
36
Example (continued)
try {
do {
.
.
LastName = Results.getString ( 2 ) ;
OR
LastName = Results.getString ( "LastName" ) ;
.
.
} while ( Results.next() );
DataRequest.close();
}
catch ( SQLException error ) {
System.err.println( "Data display error." + error );
System.exit( 5 );
}
Useful Statement Methods
• • execute Query()– Executes the SQL query and returns
the data in a table (ResultSet)– The resulting table may
be empty but never null
• ResultSet results = statement.executeQuery("SELECT
a, b FROM table");
• • executeUpdate()– Used to execute for INSERT,
UPDATE, or DELETE SQL statements
• – The return is the number of rows that were affected
in the database
37
• Supports Data Definition Language (DDL) statements
CREATE TABLE, DROP TABLE and ALTER
TABLE
int rows = statement.executeUpdate("DELETE FROM
EMPLOYEES" +"WHERE STATUS=0");
execute()– Generic method for executing stored
procedures and prepared statements
– Rarely used (for multiple return result sets)
– The statement execution may or may not return a
ResultSet (use statement.getResultSet). If the return
value is true, two or more result sets were produced
38
• getMaxRows/setMaxRows()– Determines the
maximum number of rows a ResultSet may contain
39
Result Sets consants
• Cursor Related Constants
• TYPE_FORWARD_ONLY
• style navigation in which the cursor starts at
the first row and can only move forward.
• TYPE_SCROLL_INSENSITIVE
• All cursor positioning methods are enabled;
the result set doesn’t reflect changes made by
others J2EE component in the table.
• TYPE_SCROLL_SENSITIVE
• All cursor positioning methods are enabled the
result set reflects changes made by others in
Constants in Result Sets (contd.)
• Updating Record Sets
• CONCUR_READ_ONLY
• The results set won’t be updatable
• CONCUR_UPDATABLE
• Rows can be added and deleted, and
columns can be updated.
• Closing Cursors
• HOLD_CURSORS_OVER_COMMIT
• Do not close cursors after a commit is
done.
•
Creating Scrollable Result Sets
• Statement object created with parameters to indicate
specific capabilities
• Connection.createStatement() method can have up to
three parameters:
• resultSetType – type of scrolling to be used
• resultSetConcurrency – indicates whether the result set can be
updated
• resultSetHoldability – specifies whether to close cursors when a
commit is done
• Example
• stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
JDBC 2.0 Navigation Methods for
Scrollable Result Sets
boolean next ( ) Advances the cursor to the next row.
boolean previous ( ) Moves the cursor back one row.
boolean first ( ) Moves the cursor to the first row.
boolean last ( ) Moves the cursor to the last row.
void beforeFirst ( ) Moves the cursor before the first
row,
void afterLast ( ) Moves the cursor after the last row,
boolean Moves the cursor to the specified
absolute (int row) row.
JDBC 2.0 Navigation Methods for
Scrollable Result Sets (contd.)
boolean Moves the cursor forward or
relative (int row) backward the number of rows
specified.
boolean True if the cursor is before the
isBeforeFirst ( ) first row.
boolean True if the cursor is after the
isAfterLast ( ) last row.
boolean isFirst ( ) True if the cursor is positioned
on
the first row.
boolean isLast ( ) True if the cursor is positioned on
the last row.
Constants in Result Sets (contd.)
• Updating Record Sets
• CONCUR_READ_ONLY
• The results set won’t be updatable
• CONCUR_UPDATABLE
• Rows can be added and deleted, and
columns can be updated.
• Closing Cursors
• HOLD_CURSORS_OVER_COMMIT
• Do not close cursors after a commit is
done.
•
• Three types of statement objects are available:
 Statement
• – For executing a simple SQL statement
 Prepared Statement
• – For executing a precompiled SQL statement passing
in parameters
 Callable Statement
• – For executing a database stored procedure.
46
Prepared Statements (Precompiled
Queries)
If you are going to execute similar SQL statements
multiple times, using “prepared” (parameterized)
statements can be more efficient
 Each time you use it, you simply replace some of the
marked parameters using the setXxx methods
• – execute()
• – execute Query()
• executeUpdate()
47
Prepared Statement, Example
Connection connection= DriverManager.getConnection(url,
user, password);
PreparedStatement statement
=connection.prepareStatement("UPDATE employees "+
"SET salary = ? " +"WHERE id = ?");
statement.setInt(1, sal);
statement.setInt(2, empid);
statement.executeUpdate();
48

More Related Content

What's hot

JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
SimoniShah6
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Pallepati Vasavi
 
JDBC Driver Types
JDBC Driver TypesJDBC Driver Types
JDBC Driver Types
Rahul Sharma
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
Hemo Chella
 
Jdbc
JdbcJdbc
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc
JdbcJdbc
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
Ankit Dubey
 
Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
Hemant Sharma
 
jdbc
jdbcjdbc
3 jdbc
3 jdbc3 jdbc
Jdbc
JdbcJdbc
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
Gera Paulos
 
Jdbc driver types
Jdbc driver typesJdbc driver types
Jdbc driver types
Soham Kansodaria
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
Ravinder Singh Karki
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
myrajendra
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
myrajendra
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
Middleware Training
 
Oracle Web Logic server
Oracle Web Logic serverOracle Web Logic server
Oracle Web Logic server
Rakesh Gujjarlapudi
 
Weblogic configuration
Weblogic configurationWeblogic configuration
Weblogic configuration
Aditya Bhuyan
 

What's hot (20)

JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
JDBC Driver Types
JDBC Driver TypesJDBC Driver Types
JDBC Driver Types
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
 
jdbc
jdbcjdbc
jdbc
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
 
Jdbc driver types
Jdbc driver typesJdbc driver types
Jdbc driver types
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
Oracle Web Logic server
Oracle Web Logic serverOracle Web Logic server
Oracle Web Logic server
 
Weblogic configuration
Weblogic configurationWeblogic configuration
Weblogic configuration
 

Similar to java database connection (jdbc)

Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
Pallepati Vasavi
 
java.pptx
java.pptxjava.pptx
java.pptx
bfgd1
 
Advanced JAVA
Advanced JAVAAdvanced JAVA
Advanced JAVA
Rajvi Vaghasiya
 
JDBC
JDBCJDBC
JDBC
JDBCJDBC
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
BekiTube
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
KhyalNayak
 
jdbc
jdbcjdbc
jdbc
shreeuva
 
jdbc_unit2.ppt
jdbc_unit2.pptjdbc_unit2.ppt
jdbc_unit2.ppt
JayPatel292529
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
arikazukito
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
Sandeep Rawat
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptx
BachaSirata
 
Vinay
VinayVinay
Jdbc 1
Jdbc 1Jdbc 1

Similar to java database connection (jdbc) (20)

Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Advanced JAVA
Advanced JAVAAdvanced JAVA
Advanced JAVA
 
JDBC
JDBCJDBC
JDBC
 
JDBC
JDBCJDBC
JDBC
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
 
jdbc
jdbcjdbc
jdbc
 
jdbc_unit2.ppt
jdbc_unit2.pptjdbc_unit2.ppt
jdbc_unit2.ppt
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptx
 
Vinay
VinayVinay
Vinay
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 

More from Sanjay Gunjal

Unit01_Session_07.pdf
Unit01_Session_07.pdfUnit01_Session_07.pdf
Unit01_Session_07.pdf
Sanjay Gunjal
 
Unit01_Session_06.pdf
Unit01_Session_06.pdfUnit01_Session_06.pdf
Unit01_Session_06.pdf
Sanjay Gunjal
 
Unit01_Session_04.pdf
Unit01_Session_04.pdfUnit01_Session_04.pdf
Unit01_Session_04.pdf
Sanjay Gunjal
 
Unit01_Session_03.pptx
Unit01_Session_03.pptxUnit01_Session_03.pptx
Unit01_Session_03.pptx
Sanjay Gunjal
 
Unit01_Session_05.ppt
Unit01_Session_05.pptUnit01_Session_05.ppt
Unit01_Session_05.ppt
Sanjay Gunjal
 
Unit02_Session_02 .ppt
Unit02_Session_02 .pptUnit02_Session_02 .ppt
Unit02_Session_02 .ppt
Sanjay Gunjal
 
Unit01_Session_01 .pptx
Unit01_Session_01 .pptxUnit01_Session_01 .pptx
Unit01_Session_01 .pptx
Sanjay Gunjal
 
Java script
Java scriptJava script
Java script
Sanjay Gunjal
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 

More from Sanjay Gunjal (9)

Unit01_Session_07.pdf
Unit01_Session_07.pdfUnit01_Session_07.pdf
Unit01_Session_07.pdf
 
Unit01_Session_06.pdf
Unit01_Session_06.pdfUnit01_Session_06.pdf
Unit01_Session_06.pdf
 
Unit01_Session_04.pdf
Unit01_Session_04.pdfUnit01_Session_04.pdf
Unit01_Session_04.pdf
 
Unit01_Session_03.pptx
Unit01_Session_03.pptxUnit01_Session_03.pptx
Unit01_Session_03.pptx
 
Unit01_Session_05.ppt
Unit01_Session_05.pptUnit01_Session_05.ppt
Unit01_Session_05.ppt
 
Unit02_Session_02 .ppt
Unit02_Session_02 .pptUnit02_Session_02 .ppt
Unit02_Session_02 .ppt
 
Unit01_Session_01 .pptx
Unit01_Session_01 .pptxUnit01_Session_01 .pptx
Unit01_Session_01 .pptx
 
Java script
Java scriptJava script
Java script
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 

Recently uploaded

EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptxEV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
nikshimanasa
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
wafawafa52
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
Dwarkadas J Sanghvi College of Engineering
 
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Transcat
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
Pallavi Sharma
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
q30122000
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
drshikhapandey2022
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdf
Lubi Valves
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
snaprevwdev
 
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Massimo Talia
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
Kamal Acharya
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
sydezfe
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
felixwold
 
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICSUNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
vmspraneeth
 

Recently uploaded (20)

EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptxEV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
 
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
 
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdfSELENIUM CONF -PALLAVI SHARMA - 2024.pdf
SELENIUM CONF -PALLAVI SHARMA - 2024.pdf
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdf
 
openshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoinopenshift technical overview - Flow of openshift containerisatoin
openshift technical overview - Flow of openshift containerisatoin
 
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Supermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdfSupermarket Management System Project Report.pdf
Supermarket Management System Project Report.pdf
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
 
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdfAsymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
Asymmetrical Repulsion Magnet Motor Ratio 6-7.pdf
 
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICSUNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
UNIT 4 LINEAR INTEGRATED CIRCUITS-DIGITAL ICS
 

java database connection (jdbc)

  • 1. 1 Java Database Connection (JDBC) In 1996 Sun Microsystems came out with the JDBC driver and the JDBC API. The JDBC driver is really a specification that described the detail functionality of a JDBC driver. DBMS manufactures and third-party vendors were encouraged to build JDBC drivers that conformed to Sun's specifications.
  • 2. 2 Java Database Connection (JDBC) Java programmers could then use high-level Java data objects defined in the JDBC API to write a routine that interacted with the DBMS. Java data objects convert the routine into low-level messages that conform to the JDBC driver specification and send them to the JDBC driver. The JDBC driver translates the routine into low-level messages that are understood and processed by the DBMS.
  • 3. 3 Java Database Connection (JDBC) JDBC drivers created by DBMS manufactures have to perform: • Open a connection between the DBMS and the J2EE component. • Translate low-level equivalents of SQL statements sent by the J2EE component into messages that can be processed by the DBMS. • Return data that conforms to the JDBC specification to the JDBC driver. • Return information such as error messages that conforms to the JDBC specification to the JDBC driver. • Provide transaction management routines that conform to the JDBC specification. • Close the connection between the DBMS and the J2EE component.
  • 5. 5 JDBC Driver Types JDBC drivers are classified into four groups: • Type 1 JDBC-to-ODBC Driver • Type 2 Java/Native Code Driver • Type 3 JDBC Driver • Type 4 JDBC Driver
  • 6. 6 Type 1 JDBC-to-ODBC Driver  Database Microsoft's Open Database Connection (ODBC) was used by Sun Microsystems for the basis for creating JDBC. Application Space JDBC – ODBC Bridge Database SQL Command Result Set ODBC Driver Proprietary Protocol
  • 7. Both ODBC and JDBC have similar driver specifications and API. This driver type is sometimes referred to as the JDBC/ODBC Bridge. This driver is used to translate DBMS calls between the JDBC specification and the ODBC specification.  The JDBC-to-ODBC driver receives messages from a J2EE component that conforms to the JDBC specification talked about earlier. Those messages are translated by the JDBC-to-ODBC driver into the ODBC message format, which is then translated into the message format understood by the DBMS. 7
  • 8. • Disadvantages • This type driver should not be used in a mission-critical application because the extra translation might negatively impact performance. • Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable  The client system requires the ODBC Installation to use the driver.  Not good for the Web. 8
  • 9. 9 Type 2 Java/Native Code Driver This driver uses Java classes to generate platform- specific code (code that is only understood by a specific Java Application Application Space Type 2 JDBC Driver Database SQL Command Result Set Native Database Library Proprietary Protocol
  • 10.  The manufacturer of the DBMS provides both the Java/Native Code driver and API classes so the J2EE component can generate the platform specific-code. •Example: Oracle will have oracle native api. •Advantage •The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native api which is Database specific. 10
  • 11. • Disadvantage • 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue. 3. If we change the Database we have to change the native api as it is specific to a database 11
  • 12. 12 Type 3 JDBC Driver All Java/Net-protocol driver Application Space Java Application Type 3 JDBC Driver Database SQL Command Result Set Middleware Component Proprietary Protocol Server
  • 13. • Translates JDBC calls into a database-independent network protocol and sent to a middleware server. • This server translates this DBMS-independent protocol into a DBMS-specific protocol and sent to the database • Results sent back to the middleware and routed to the client 13
  • 14. Advantages • 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is fully written in Java and hence Portable. It is suitable for the web. 3. There are many opportunities to optimize portability, performance, and scalability. 4. The net protocol can be designed to make the client JDBC driver very small and fast to load. 5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. 14
  • 15. • Disadvantage • It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server. 15
  • 16. 16 Type 4 JDBC Driver Native-protocol/all-Java driver Application Space Java Application Type 4 JDBC Driver Database SQL Command Using Proprietary Protocol Result Set Using Proprietary Protocol
  • 17. • This driver type is also known as the Type 4 database protocol. • It is similar to the Type 3 JDBC driver except SQL queries are translated into the format required by the DBMS. • SQL queries do not need to be converted to JDBC- formatted systems. This is the fastest way to communicate SQL queries to the DBMS. 17
  • 18. • Advantage • 1. A type 4 jdbc drivers are that they are completely written in Java to achieve platform independence 2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. 3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically. • Disadvantage 18
  • 19. 19 JDBC Packages The JDBC API is contained in two packages. • java.sql • javax.sql
  • 20. 20 java.sql This package contains core Java data objects of the JDBC API. These include Java data objects that provide the basis for connecting to the DBMS and interacting with the data stored in the DBMS. java.sql is part of the J2SE. To use this package in a Java application you must use the following: import java.sql.*;
  • 21. 21 javax.sql This package contains the JDBC API. javax.sql extends java.sql and is in the J2EE. Included in this package are the Java data objects that interact with Java Naming and Directory Interface (JNDI) and the Java data objects that manage connection pooling, among other advanced JDBC features. To use this package in a Java application you must use the following: import javax.sql.*;
  • 22. JDBC Concepts • JDBC’s design is very similar to the design of ODBC • Driver Manager • Loads database drivers, and manages the connection between the application and the driver • Driver • Translates API calls into operations for a specific data source • Connection • A session between an application and a database
  • 23. JDBC Concepts (contd.) • Statement • An SQL Statement to perform a query or update operation • Metadata • Information about returned data, the database and the driver • ResultSet • Logical set of columns and rows returned by executing an SQL statement (resulting tuples)
  • 24. Steps Involved in Basic JDBC Operations Driver Driver Manager Connection Statement Result Set 1. Load the JDBC driver class: Class.forName(“driverName”); 2. Open a database connection: DriverManager.getConnection (“jdbc:xxx:datasource”); 3. Issue SQL statements: stmt = con.createStatement(); stmt.executeQuery (“Select * from myTable”); 4. Process result set: while (rs.next()) { name = rs.getString(“name”); amount = rs.getInt(“amt”); } Database
  • 25. 25 A Brief Overview of the JDBC Process 1. Loading the JDBC driver 2. Connecting to the DBMS 3. Creating and executing a statement (like a SQL query) 4. Processing data returned by the DBMS (a result set) 5. Terminating the connection with the DBMS
  • 26. 26 Loading the JDBC driver The JDBC driver must be loaded before the J2EE component can connect to the DBMS.  The Class.forName() method is used to load the JDBC driver.  For Ex.
  • 27. 27 Loading the JDBC driver - Example import java.sql.*; class Dboperation { public static void main(String args[]) { try { Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); } catch ( ClassNotFoundException e ) { System.out.println( "classname not found '" + e.getMessage() + "'" ); System.exit( 0 ); } catch (SQLException error) { System.err.println("Cannot connect to the database." + error); System.exit( ); }}}
  • 28. 28 Connect to the DBMS Once the driver is loaded, the J2EE component must connect to the DBMS using the The DriverManager.getConnection() method is passed the URL of the database, and the user ID and password if required by the DBMS. The URL is a String object that contains the driver name and the Data source name. The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database that is being accessed by the J2EE component.
  • 29. 29 Connect to the DBMS Example import java.sql.*; class Dboperation { public static void main(String args[]) { private String url = "jdbc:odbc:data source name"; private String userID = “ "; private String password = “ "; private static Connection Db; try { Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); Db = DriverManager.getConnection( url, userID, password );} catch ( ClassNotFoundException e ) { System.out.println( "classname not found '" + e.getMessage() + "'" ); System.exit( 0 );} catch (SQLException error) { System.err.println( "Cannot connect to the database." + error ); System.exit( );} }}
  • 30. 30 Create and Execute a SQL Statement The Connect.createStatement() method is used to create a Statement object. The resulting Statement object is then used to execute a query and return a Result Set object that contains the response from the DBMS. This response is usually one or more rows of information requested by the J2EE component. For ex. private Statement DataRequest; DataRequest=Db.createStatement(); Typically, the query is assigned to a String object, which is passed to the object's execute Query() method. Once the Result Set is received from the DBMS, the close() method is called to terminate the statement.
  • 31. 31 Create and Execute a SQL Statement - Example import java.sql.*; class Dboperation { public static void main(String args[]) { private static Connection Db; // Connection object from above private Statement Data Request; // create a Statement object private Result Set Results; // create a ResultSet object try { // build SQL query in a String object String query = "SELECT ... FROM table-name"; DataRequest = Db.createStatement(); Results = DataRequest.executeQuery( query ); } catch ( SQLException error ){ System.err.println( "SQL error." + error ); System.exit( 3 ); }}}
  • 32. 32 Processing Data Returned by the DBMS The java.sql.ResultSet object is assigned the results received from the DBMS after the query is processed. It also consists of methods used to interact with data that is returned by the DBMS to the J2EE component. Some of the methods used are the next(), getString(), getxxx(), and close() methods.
  • 33. 33 next( ) method Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
  • 34. 34 close() method Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re- executed, or is used to retrieve the next result from a sequence of multiple results. A ResultSet object is also automatically closed
  • 35. 35 Example import java.sql.*; private String LastName; private boolean Records; // used for the next() method . . try { Records = Results.next(); if ( !Records ) { System.out.println( "No data returned" ); System.exit( 4 ); } } catch ( SQLException error ) { System.err.println( "SQL error." + error ); System.exit( 3 ); }
  • 36. 36 Example (continued) try { do { . . LastName = Results.getString ( 2 ) ; OR LastName = Results.getString ( "LastName" ) ; . . } while ( Results.next() ); DataRequest.close(); } catch ( SQLException error ) { System.err.println( "Data display error." + error ); System.exit( 5 ); }
  • 37. Useful Statement Methods • • execute Query()– Executes the SQL query and returns the data in a table (ResultSet)– The resulting table may be empty but never null • ResultSet results = statement.executeQuery("SELECT a, b FROM table"); • • executeUpdate()– Used to execute for INSERT, UPDATE, or DELETE SQL statements • – The return is the number of rows that were affected in the database 37
  • 38. • Supports Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE and ALTER TABLE int rows = statement.executeUpdate("DELETE FROM EMPLOYEES" +"WHERE STATUS=0"); execute()– Generic method for executing stored procedures and prepared statements – Rarely used (for multiple return result sets) – The statement execution may or may not return a ResultSet (use statement.getResultSet). If the return value is true, two or more result sets were produced 38
  • 39. • getMaxRows/setMaxRows()– Determines the maximum number of rows a ResultSet may contain 39
  • 40. Result Sets consants • Cursor Related Constants • TYPE_FORWARD_ONLY • style navigation in which the cursor starts at the first row and can only move forward. • TYPE_SCROLL_INSENSITIVE • All cursor positioning methods are enabled; the result set doesn’t reflect changes made by others J2EE component in the table. • TYPE_SCROLL_SENSITIVE • All cursor positioning methods are enabled the result set reflects changes made by others in
  • 41. Constants in Result Sets (contd.) • Updating Record Sets • CONCUR_READ_ONLY • The results set won’t be updatable • CONCUR_UPDATABLE • Rows can be added and deleted, and columns can be updated. • Closing Cursors • HOLD_CURSORS_OVER_COMMIT • Do not close cursors after a commit is done. •
  • 42. Creating Scrollable Result Sets • Statement object created with parameters to indicate specific capabilities • Connection.createStatement() method can have up to three parameters: • resultSetType – type of scrolling to be used • resultSetConcurrency – indicates whether the result set can be updated • resultSetHoldability – specifies whether to close cursors when a commit is done • Example • stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
  • 43. JDBC 2.0 Navigation Methods for Scrollable Result Sets boolean next ( ) Advances the cursor to the next row. boolean previous ( ) Moves the cursor back one row. boolean first ( ) Moves the cursor to the first row. boolean last ( ) Moves the cursor to the last row. void beforeFirst ( ) Moves the cursor before the first row, void afterLast ( ) Moves the cursor after the last row, boolean Moves the cursor to the specified absolute (int row) row.
  • 44. JDBC 2.0 Navigation Methods for Scrollable Result Sets (contd.) boolean Moves the cursor forward or relative (int row) backward the number of rows specified. boolean True if the cursor is before the isBeforeFirst ( ) first row. boolean True if the cursor is after the isAfterLast ( ) last row. boolean isFirst ( ) True if the cursor is positioned on the first row. boolean isLast ( ) True if the cursor is positioned on the last row.
  • 45. Constants in Result Sets (contd.) • Updating Record Sets • CONCUR_READ_ONLY • The results set won’t be updatable • CONCUR_UPDATABLE • Rows can be added and deleted, and columns can be updated. • Closing Cursors • HOLD_CURSORS_OVER_COMMIT • Do not close cursors after a commit is done. •
  • 46. • Three types of statement objects are available:  Statement • – For executing a simple SQL statement  Prepared Statement • – For executing a precompiled SQL statement passing in parameters  Callable Statement • – For executing a database stored procedure. 46
  • 47. Prepared Statements (Precompiled Queries) If you are going to execute similar SQL statements multiple times, using “prepared” (parameterized) statements can be more efficient  Each time you use it, you simply replace some of the marked parameters using the setXxx methods • – execute() • – execute Query() • executeUpdate() 47
  • 48. Prepared Statement, Example Connection connection= DriverManager.getConnection(url, user, password); PreparedStatement statement =connection.prepareStatement("UPDATE employees "+ "SET salary = ? " +"WHERE id = ?"); statement.setInt(1, sal); statement.setInt(2, empid); statement.executeUpdate(); 48