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

PPT
Unit 5-jdbc2
PPTX
Jdbc drivers
PPT
Jdbc drivers
DOC
jdbc document
PPTX
Jdbc
PPT
PPTX
Jdbc introduction
DOCX
Jdbc driver types
Unit 5-jdbc2
Jdbc drivers
Jdbc drivers
jdbc document
Jdbc
Jdbc introduction
Jdbc driver types

What's hot (20)

PPT
JDBC Architecture and Drivers
PPT
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
PPTX
JDBC Driver Types
PPT
Chap3 3 12
PPT
PDF
Ajp notes-chapter-05
PPTX
Types of Drivers in JDBC
PPT
PDF
PDF
Java Database Connectivity (Advanced programming)
PPTX
Jdbc driver types
PPTX
Jdbc_ravi_2016
PPTX
Interface callable statement
PPTX
Java.sql package
PDF
Java Introduction
PDF
Oracle Web Logic server
PDF
Weblogic configuration
JDBC Architecture and Drivers
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC Driver Types
Chap3 3 12
Ajp notes-chapter-05
Types of Drivers in JDBC
Java Database Connectivity (Advanced programming)
Jdbc driver types
Jdbc_ravi_2016
Interface callable statement
Java.sql package
Java Introduction
Oracle Web Logic server
Weblogic configuration
Ad

Similar to java database connection (jdbc) (20)

DOC
PPTX
Advanced JAVA
PPTX
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
PDF
PPT
4-INTERDUCATION TO JDBC-2019.ppt
PPT
PPTX
java.pptx
PPTX
Java jdbc
PPT
Mobile Application Devlopement-Database connections-UNIT-5
PPT
Jdbc complete
PPT
Accessing Database using jdbc Template and record set
PPT
unit-v-17071204384654656646455455448.ppt
PPTX
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
PPT
Unit 1 Advance Java - JDBC.ppt
PPTX
Chapter_4_-_JDBC[1].pptx
PPTX
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
PPT
Jdbc ppt
PPTX
Java Database Connectivity (JDBC)
PPT
open data base connectivity and java database connectivity
PPT
JDBC java database connectivity with dbms
Advanced JAVA
jdbc.pptx jdbc.pptxjdbc.pptxjdbc.pptxjdb
4-INTERDUCATION TO JDBC-2019.ppt
java.pptx
Java jdbc
Mobile Application Devlopement-Database connections-UNIT-5
Jdbc complete
Accessing Database using jdbc Template and record set
unit-v-17071204384654656646455455448.ppt
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
Unit 1 Advance Java - JDBC.ppt
Chapter_4_-_JDBC[1].pptx
UNIT 1 PPT- FINAL.pptx Advance Java JDBC
Jdbc ppt
Java Database Connectivity (JDBC)
open data base connectivity and java database connectivity
JDBC java database connectivity with dbms
Ad

More from Sanjay Gunjal (9)

PDF
Unit01_Session_07.pdf
PDF
Unit01_Session_06.pdf
PDF
Unit01_Session_04.pdf
PPTX
Unit01_Session_03.pptx
PPT
Unit01_Session_05.ppt
PPT
Unit02_Session_02 .ppt
PPTX
Unit01_Session_01 .pptx
PDF
Java script
PPT
Java programming concept
Unit01_Session_07.pdf
Unit01_Session_06.pdf
Unit01_Session_04.pdf
Unit01_Session_03.pptx
Unit01_Session_05.ppt
Unit02_Session_02 .ppt
Unit01_Session_01 .pptx
Java script
Java programming concept

Recently uploaded (20)

PPTX
“Next-Gen AI: Trends Reshaping Our World”
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
PPTX
Road Safety tips for School Kids by a k maurya.pptx
PPTX
anatomy of limbus and anterior chamber .pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
DOCX
573137875-Attendance-Management-System-original
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PPTX
AgentX UiPath Community Webinar series - Delhi
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
ETO & MEO Certificate of Competency Questions and Answers
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
“Next-Gen AI: Trends Reshaping Our World”
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
OOP with Java - Java Introduction (Basics)
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
Road Safety tips for School Kids by a k maurya.pptx
anatomy of limbus and anterior chamber .pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
573137875-Attendance-Management-System-original
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
AgentX UiPath Community Webinar series - Delhi
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
ETO & MEO Certificate of Competency Questions and Answers
Lesson 3_Tessellation.pptx finite Mathematics
Chapter 6 Design in software Engineeing.ppt
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx

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