Java Data Base Connectivity Java Data Base Connectivity By CHITRAKANT BANCHHOR
Java Data Base ConnectivityJava Data Base ConnectivityBy
CHITRAKANT BANCHHOR
ReferencesReferences
1. Introduction1. Introduction
ODBC (Open Data Base Connectivity)ODBC (Open Data Base Connectivity)
ODBC API from Microsoft for database access
FunctionsProvides
4
Functions
Insert
Delete
Modify
Obtaining Information
Provides
How ODBC Connection takes place?How ODBC Connection takes place?
ApplicationODBC
InterfaceODBC
InterfaceDriver
ManagerDriver
Manager
AccessDriver
AccessDriver
OracleDriverOracleDriver
AccessDatabase
AccessDatabase
OracleDatabase
OracleDatabase
5
• Application could be a GUI program
• Makes use of ODBC to interact with databases
• Driver Manager is part of Microsoft ODBC and is used to manage
various drivers in the system
ApplicationODBC
InterfaceODBC
InterfaceDriver
ManagerDriver
ManagerOracleDriverOracleDriver
……
OracleDatabase
……
What is JDBC?What is JDBC?
JDBC Actually an Application Programming Interface (API)
Consists of
6
Java Classes InterfacesExceptions bound to
specifications
Need for JDBCNeed for JDBC• ODBC uses a C interface that has lots of drawbacks.
• A Java API like JDBC is needed in order to enable a “pure Java” solution.
• JDBC is a standard interface for Java programmers to access relationaldatabases
• ODBC uses a C interface that has lots of drawbacks.
• A Java API like JDBC is needed in order to enable a “pure Java” solution.
• JDBC is a standard interface for Java programmers to access relationaldatabases
Structure of JDBCStructure of JDBC
JDBC
Application A Application B
SybaseOracle MySql
JDBC Hide the specifics of each database
Programmer just concentrate onapplications
Uses
Programmer just concentrate onapplications
Set of Interfaces: Implemented differently from DBMS Vendors
Set of Classes: that implement the JDBC interfaces for a particulardatabase engine is called a JDBC driver
2. Understanding the JDBC2. Understanding the JDBCArchitectureArchitecture
10
2. Understanding the JDBC2. Understanding the JDBCArchitectureArchitecture
JDBC ArchitectureJDBC Architecture
• The JDBC API supports both two-tier and three-tier models for databaseaccess.
• In other words, JDBC can either be used directly from our application or aspart of a middle-tier server application.
• Two-tier Processing Models
• Three-tier Processing Models
11
• The JDBC API supports both two-tier and three-tier models for databaseaccess.
• In other words, JDBC can either be used directly from our application or aspart of a middle-tier server application.
• Two-tier Processing Models
• Three-tier Processing Models
TwoTwo--tier Processing Modelstier Processing Models
JavaApplication
JavaApplication
DBMSDBMS
with the
DBMSDBMS
Application Functionality
Application Layer Database LayerApplication Layer Database Layer
JDBC Driver Business Logic
User InterfaceRDBMS
TwoTwo--tier Architecture for Data Access Cont.tier Architecture for Data Access Cont.
Java Application
JDBCClient MachineClient Machine
DBMS Proprietary ProtocolDBMS Proprietary Protocol
DBMS
DBMS Proprietary ProtocolDBMS Proprietary Protocol
Database ServerDatabase Server
JDBC DriverJDBC Driver
Client LayerClient LayerClientClient
DataDataServerServer
Server LayerServer Layer
Client Layer
Application/presentation layer
TransactionManagement
BusinessLogic
ConnectionManagement
Responsiblefor
Server Layer
Data Source
ThreeThree--tier Architecture for Data Accesstier Architecture for Data Access
Java applet or HTML browser
Application Server(Java)
Server MachineServer Machine( Business Logic)( Business Logic)
Client Machine (GUI)Client Machine (GUI)
HTTP, RMI, CORBA or other calls
Application Server(Java)
JDBC
DBMSDatabase server
DBMS Proprietary ProtocolDBMS Proprietary Protocol
Server MachineServer Machine( Business Logic)( Business Logic)
ApplicationsApplication Servers
DriversTransaction Management
Thin ClientsThin Clients
Client LayerClient Layer
DataDataDataData DataData
ApplicationsApplication Servers
DriversTransaction Management
ServerServer
Server Layer
Middle LayerMiddle Layer
The main components of a threeThe main components of a three--tier architecture aretier architecture are
Client Tier
Typically a thinpresentation layer
Browser
Middle TierMiddle Tier
Handles Business Logicor Application Logic
JDBC Driver
Application Server (Jboss Server)Application Server (Jboss Server)
Data Source Layer
RDBMSRDBMS
JDBC DriversJDBC Drivers
•• JDBC Consists of two parts:JDBC Consists of two parts:
1.1. JDBCJDBC APIAPI a purely java based API.
2.2. JDBC DriverJDBC Driver ManagerManager which communicates with vendor –specific drivers that performs the real communication with thedatabase.
20
•• JDBC Consists of two parts:JDBC Consists of two parts:
1.1. JDBCJDBC APIAPI a purely java based API.
2.2. JDBC DriverJDBC Driver ManagerManager which communicates with vendor –specific drivers that performs the real communication with thedatabase.
Java application
JDBC Driver Manager
JDBC-ODBC Bridge Vendor specificJDBC Driver
JDBC DriverAPI
JDBC API
21
JDBC-ODBC Bridge Vendor specificJDBC Driver
Vendor specificODBC Driver
Type 1Type 1
JDBCJDBC--ODBC BridgeODBC Bridge plus ODBC Driver.
JDBCJDBC -- ODBCODBCbridgebridge
Database ServerOracleODBC Driver
22
JDBCJDBC -- ODBCODBCbridgebridge
Database ServerSQL Server
ODBC Driver
DataBase-client
Type -1Driver
Type -1Driver
JDBC CallsODBCDriverODBCDriver
ODBC CallsType -1Driver
ODBCDriver
Translates all JDBC Calls intoODBC calls
DBMSDBMS
• The JDBCJDBC--ODBC Bridge driverODBC Bridge driver is recommended only for experimental use orwhen no other alternative is available.
Java Application
JDBC API
Bridge Driver
DSN
Driver
Data
ODBCODBC
How it works ?How it works ?
DriverType - 1Driver
Type - 1
JDBC QueryJDBC Query ODBC QueryODBC QueryODBCDriverODBCDriver
Translates into corresponding ODBCQuery and hands over to ODBC Driver
Sun provides a JDBC-ODBC Bridge driver.sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and notJava, and is closed source.
Type – 1Driver
Type – 1Driver
AdvantageAdvantage
The JDBC-ODBC Bridge allows access toalmost any database, since the database'sODBC drivers are already available.
Portability issue: Bridge driver is not written fullyin Java, Type 1 drivers are not portable.
Type – 1Driver
Disadvantages
Portability issue: Bridge driver is not written fullyin Java, Type 1 drivers are not portable.
ODBC Installation: The client system requires theODBC Installation to use the driver
Performance issue: JDBC call goes through thebridge to the ODBC driver, then to the database,and this applies even in the reverse process.
Type – 2Driver
Type – 2Driver
JDBC api calls
Oracle DBMSOracle DBMS
for Oracle
Type2:Type2: Java Native Interface DriverJava Native Interface Driver(( NativeNative--API / partly Java driverAPI / partly Java driver )
Oracle DBMSOracle DBMS
Sybase DBMSSybase DBMS
Informix DBMSInformix DBMS
Java Application
JDBC API
Native API Driver
Database LibraryDatabase Library(Native Code)(Native Code)
Type 2 JDBC DriverType 2 JDBC Driver(Java)(Java)
Native API
Data
Database LibraryDatabase Library(Native Code)(Native Code)
• They mainly use the Java Native Interface (JNI) to translate calls to the localdatabase API.
• That is, this driver is specific to a particular database.
• Example: Oracle will have oracle native api.
• They mainly use the Java Native Interface (JNI) to translate calls to the localdatabase API.
• That is, this driver is specific to a particular database.
• Example: Oracle will have oracle native api.
How it works ?How it works ?
DriverType - 2
DriverType - 2
JDBC CallsJDBC Calls Client APIClient API
DBMSDBMS
converts JDBC calls into calls to theclient API for that database
Client -> JDBC Driver -> Vendor Client DB Library -> Database.
Type – 2Driver
Type – 2Driver
AdvantageAdvantage
Performance Issues: Better than the JDBC-ODBCBridge as the layers of communication (tiers) areless than that of Type 1 and also it uses Native apiwhich is Database specific.
Portability issue: not written in Java, Type 2drivers are not portable.
Type – 2Driver
Disadvantages
Portability issue: not written in Java, Type 2drivers are not portable.
Native Installation: Native API must be installedin the Client System and hence type 2 driverscannot be used for the Internet.
If we change the Database we have to change thenative api as it is specific to a database.
Mostly obsolete now
Type 3:Type 3: All Java/NetAll Java/Net--protocol driver (protocol driver (MiddlewareMiddleware))
• Type 3 JDBC drivers are pure Java drivers for database middleware.
Type – 3Driver
Type – 3Driver
JDBC api callsDBMS – Independent
Net ProtocolsDBMS – Independent
Net Protocols
Translates
Server( Middleware Component )
DBMSDBMS Translated into DBMS Protocol
Java Application
JDBC API
Type - 3 Driver
Or ServerOr Server
net Common Protocolnet Common Protocol
MiddlewareComponent
Data
Or ServerOr Server
How it works ?How it works ?
DriverType - 3
DriverType - 3
Request for dataRequest for data
TranslatesTranslatesintointoDatabaseDatabaseCommandsCommands
Middlewarenet-server
Middlewarenet-server
This Driver communicates withmiddleware net – servercommunicates using databaseindependent protocol.
DBMSDBMS
CommunicatesCommunicatesusing databaseusing databaseindependentindependentprotocolprotocol
This Driver communicates withmiddleware net – servercommunicates using databaseindependent protocol.
Client -> JDBC Driver -> Middleware-Net Server -> Any Database
Type – 3Driver
Type – 3Driver
DisadvantageDisadvantageIt requires another server application to install andmaintain
No vendor specific database library: This driver isserver-based, so there is no need for any vendordatabase library to be present on client machines.
Type – 3Driver
Advantages
No vendor specific database library: This driver isserver-based, so there is no need for any vendordatabase library to be present on client machines.
This driver is very flexible allows access tomultiple databases using one driver.
Portable: This driver is fully written in Java andhence Portable. It is suitable for the web.
Type -4DriverType -4Driver
JDBC api callsNetwork Protocols
Used by DBMS directlyNetwork Protocols
Used by DBMS directly
Translates into
Type 4: pure Java driver for directType 4: pure Java driver for direct--toto--databasedatabase
DBMSDBMS
Java Application
JDBC API
Thin, Type - 4 DriverNative protocolNative protocol
Uses Networking librariesUses Networking libraries
Thin, Type - 4 Driver
Data
Native protocolNative protocol
• The Type 4 uses java networking libraries to communicate directly with thedatabase server.
• Type 4 JDBC drivers are direct-to-database pure Java drivers ("thin" drivers).
• A Type 4 driver takes JDBC calls and translates them into the networkprotocol (proprietary protocol) used directly by the DBMS.
• The Type 4 uses java networking libraries to communicate directly with thedatabase server.
• Type 4 JDBC drivers are direct-to-database pure Java drivers ("thin" drivers).
• A Type 4 driver takes JDBC calls and translates them into the networkprotocol (proprietary protocol) used directly by the DBMS.
How it works ?How it works ?
DriverType - 4
DriverType - 4
JDBC callsJDBC calls
Converts JDBC calls into the vendor-specific database protocol
DBMSDBMS
Client Application directly CommunicatesClient Application directly Communicatesto the Database Serverto the Database Server
Example: oracle.jdbc.driver. OracleDriver
Type – 4Driver
Type – 4Driver
DisadvantageDisadvantageDatabase specific driver: With type 4 drivers, the userneeds a different driver for each database.
Reduced Number of translation layers: type 4 JDBCdrivers don't have to translate database requests toODBC or a native connectivity interface or to passthe request on to another server, performance istypically quite good.
Type – 4Driver
Advantages
Reduced Number of translation layers: type 4 JDBCdrivers don't have to translate database requests toODBC or a native connectivity interface or to passthe request on to another server, performance istypically quite good.
We don’t need to install special software on theclient or server.
Portable: This driver is fully written in Java andhence Portable. It is most suitable for the web.
3. Seven Basic steps of using JDBC3. Seven Basic steps of using JDBC
42
Load the driverLoad the driver11
Define the connection URLDefine the connection URL22
Establish the connectionEstablish the connection33
Create a Statement objectCreate a Statement object444
Execute a queryExecute a query55
Process the resultsProcess the results66
Close the connectionClose the connection77
12
3
4
Creating a JDBC application
BeginBegin
Import thejava.sql package
Import thejava.sql package
Load andRegister the driver
Load andRegister the driver
Create aConnection object
Create aConnection object
44
4
5
6
7 8
Create aConnection object
Create aConnection object
Create aStatement object
Create aStatement object
Execute thestatement
Execute thestatement
Close ConnectionClose Connection
EndEnd
12
3
4
Creating a JDBC application
Begin
Import thejava.sql package
Load andRegister the driver
Create aConnection object
Class.Class. forNameforName (“sun.jdbc.odbc.JdbcOdbcDriver”);
ConnectionConnection con =DriverManager.getConnection(msAccessURL,);
45
4
5
6
7 8
Create aConnection object
Create aStatement object
Execute thestatement
Close Connection
End
StatementStatement stmt = con.createStatementcon.createStatement();
ResultSetResultSet rs = stmt.stmt.executeQueryexecuteQuery(SELECT * FROM STD);
Load the driverLoad the driverLoad the driverLoad the driver11
• It is necessary to load the JDBC drivers before attempting to connect to thedatabase.
• The JDBC drivers automatically register themselves with the JDBC systemwhen loaded.
46
try {
Class.Class. forNameforName (“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch (ClassNotFoundExceptionClassNotFoundException cnfe){
System.out.println(“Error loading driver” + cnfe);
}
try {
Class.Class. forNameforName (“sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch (ClassNotFoundExceptionClassNotFoundException cnfe){
System.out.println(“Error loading driver” + cnfe);
}
Define the connection URLDefine the connection URLDefine the connection URLDefine the connection URL22
StringString msAccessURL = “jdbc:odbc:datasource”;
• Make the connection with the database server.
• In the Establishing Connection step we will logon to the database with username and password.
Establish the connectionEstablish the connectionEstablish the connectionEstablish the connection33
49
ConnectionConnection con = DriverManager.getConnection(msAccessURL, userName, passWORD);
StatementStatement stmt = con.createStatementcon.createStatement();
Create a Statement objectCreate a Statement objectCreate a Statement objectCreate a Statement object44
Execute a queryExecute a queryExecute a queryExecute a query55
50
StringString Query = “SELECT * FROM Student”;ResultSetResultSet rs = stmt.stmt.executeQueryexecuteQuery(Query);
Process the resultsProcess the resultsProcess the resultsProcess the results66
• In this step we receive the result of execute statement.
• In this case we will fetch the student records from the recordset object andshow on the console.
51
whilewhile( rs.nextrs.next() ) {System.out.print(rs.getInt(1) + “\t”);System.out.print(rs.getString(“RollNo”) + “\t”);System.out.println();
}
con.closecon.close();();
Close the connectionClose the connectionClose the connectionClose the connection77
Example 1Example 1
53
Example2
54
55
Example3
56
Example4
57
58
Thank You!Thank You!Thank You!Thank You!