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 (20)

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
Mumbai Academisc
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
Centre for Budget and Governance Accountability (CBGA)
 
Jdbc
JdbcJdbc
Jdbc
myrajendra
 
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
jdbc
Gayatri Patel
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
Fajar Baskoro
 
Jdbc
JdbcJdbc
Jdbc
Mumbai Academisc
 
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
 

Similar to java database connection (jdbc) (20)

JDBC
JDBCJDBC
JDBC
Manjunatha RK
 
Advanced JAVA
Advanced JAVAAdvanced JAVA
Advanced JAVA
Rajvi Vaghasiya
 
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdbjdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
devamrana27
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
Mukesh Tekwani
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
Jdbcdriver
JdbcdriverJdbcdriver
Jdbcdriver
Manisha Shinde-Pawar
 
java.pptx
java.pptxjava.pptx
java.pptx
bfgd1
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
AliHusseini14
 
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
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
Sandeep Rawat
 
Accessing Database using jdbc Template and record set
Accessing Database using jdbc Template and record setAccessing Database using jdbc Template and record set
Accessing Database using jdbc Template and record set
gangishettysaikrishn
 
unit-v-17071204384654656646455455448.ppt
unit-v-17071204384654656646455455448.pptunit-v-17071204384654656646455455448.ppt
unit-v-17071204384654656646455455448.ppt
AnmolMogalai
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Unit 1 Advance Java - JDBC.ppt
Unit 1 Advance Java -           JDBC.pptUnit 1 Advance Java -           JDBC.ppt
Unit 1 Advance Java - JDBC.ppt
creativegamerz00
 
Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptx
BachaSirata
 
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
UNIT 1 PPT- FINAL.pptx Advance Java JDBCUNIT 1 PPT- FINAL.pptx Advance Java JDBC
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
iamspidey0104
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
open data base connectivity and java database connectivity
open data base connectivity and java database connectivityopen data base connectivity and java database connectivity
open data base connectivity and java database connectivity
ssuser42b933
 
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.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdbjdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
devamrana27
 
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.pptx
java.pptxjava.pptx
java.pptx
bfgd1
 
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
 
Accessing Database using jdbc Template and record set
Accessing Database using jdbc Template and record setAccessing Database using jdbc Template and record set
Accessing Database using jdbc Template and record set
gangishettysaikrishn
 
unit-v-17071204384654656646455455448.ppt
unit-v-17071204384654656646455455448.pptunit-v-17071204384654656646455455448.ppt
unit-v-17071204384654656646455455448.ppt
AnmolMogalai
 
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Unit 1 Advance Java - JDBC.ppt
Unit 1 Advance Java -           JDBC.pptUnit 1 Advance Java -           JDBC.ppt
Unit 1 Advance Java - JDBC.ppt
creativegamerz00
 
Chapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptxChapter_4_-_JDBC[1].pptx
Chapter_4_-_JDBC[1].pptx
BachaSirata
 
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
UNIT 1 PPT- FINAL.pptx Advance Java JDBCUNIT 1 PPT- FINAL.pptx Advance Java JDBC
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
iamspidey0104
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
Pooja Talreja
 
open data base connectivity and java database connectivity
open data base connectivity and java database connectivityopen data base connectivity and java database connectivity
open data base connectivity and java database connectivity
ssuser42b933
 
JDBC java database connectivity with dbms
JDBC java database connectivity with dbmsJDBC java database connectivity with dbms
JDBC java database connectivity with dbms
KhyalNayak
 
Ad

More from Sanjay Gunjal (9)

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
 
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 programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
Ad

Recently uploaded (20)

362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDSWater demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its ApplicationEngineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
TEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design exampleTEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design example
ssuser1be9ce
 
First Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptxFirst Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptx
KavitaBagewadi2
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdfOCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cellsGreat power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for  diesel tank.docxCenter Enamel can Provide Aluminum Dome Roofs for  diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Water demand - Types , variations and WDS
Water demand - Types , variations and WDSWater demand - Types , variations and WDS
Water demand - Types , variations and WDS
dhanashree78
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its ApplicationEngineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
TEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design exampleTEA2016AAT 160 W TV application design example
TEA2016AAT 160 W TV application design example
ssuser1be9ce
 
First Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptxFirst Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptx
KavitaBagewadi2
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdfOCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cellsGreat power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for  diesel tank.docxCenter Enamel can Provide Aluminum Dome Roofs for  diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 

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