Top Banner
Java Data Base Connectivity Java Data Base Connectivity By CHITRAKANT BANCHHOR
59

Java DataBase Connectivity -JDBC Part-1

Dec 06, 2014

Download

Education

Pranil Dukare

JDBC Part-1,
This was made by Prof. Chitrakant Banchhor
Very Descriptive,Easy to Understand
Thank You Sir......
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java DataBase Connectivity -JDBC Part-1

Java Data Base ConnectivityJava Data Base ConnectivityBy

CHITRAKANT BANCHHOR

Page 2: Java DataBase Connectivity -JDBC Part-1

ReferencesReferences

Page 3: Java DataBase Connectivity -JDBC Part-1

1. Introduction1. Introduction

Page 4: Java DataBase Connectivity -JDBC Part-1

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

Page 5: Java DataBase Connectivity -JDBC Part-1

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

……

Page 6: Java DataBase Connectivity -JDBC Part-1

What is JDBC?What is JDBC?

JDBC Actually an Application Programming Interface (API)

Consists of

6

Java Classes InterfacesExceptions bound to

specifications

Page 7: Java DataBase Connectivity -JDBC Part-1

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

Page 8: Java DataBase Connectivity -JDBC Part-1

Structure of JDBCStructure of JDBC

JDBC

Application A Application B

SybaseOracle MySql

Page 9: Java DataBase Connectivity -JDBC Part-1

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

Page 10: Java DataBase Connectivity -JDBC Part-1

2. Understanding the JDBC2. Understanding the JDBCArchitectureArchitecture

10

2. Understanding the JDBC2. Understanding the JDBCArchitectureArchitecture

Page 11: Java DataBase Connectivity -JDBC Part-1

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

Page 12: Java DataBase Connectivity -JDBC Part-1

TwoTwo--tier Processing Modelstier Processing Models

JavaApplication

JavaApplication

DBMSDBMS

with the

DBMSDBMS

Page 13: Java DataBase Connectivity -JDBC Part-1

Application Functionality

Application Layer Database LayerApplication Layer Database Layer

JDBC Driver Business Logic

User InterfaceRDBMS

Page 14: Java DataBase Connectivity -JDBC Part-1

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

Page 15: Java DataBase Connectivity -JDBC Part-1

JDBC DriverJDBC Driver

Client LayerClient LayerClientClient

DataDataServerServer

Server LayerServer Layer

Page 16: Java DataBase Connectivity -JDBC Part-1

Client Layer

Application/presentation layer

TransactionManagement

BusinessLogic

ConnectionManagement

Responsiblefor

Server Layer

Data Source

Page 17: Java DataBase Connectivity -JDBC Part-1

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)

Page 18: Java DataBase Connectivity -JDBC Part-1

ApplicationsApplication Servers

DriversTransaction Management

Thin ClientsThin Clients

Client LayerClient Layer

DataDataDataData DataData

ApplicationsApplication Servers

DriversTransaction Management

ServerServer

Server Layer

Middle LayerMiddle Layer

Page 19: Java DataBase Connectivity -JDBC Part-1

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

Page 20: Java DataBase Connectivity -JDBC Part-1

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.

Page 21: Java DataBase Connectivity -JDBC Part-1

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

Page 22: Java DataBase Connectivity -JDBC Part-1

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

Page 23: Java DataBase Connectivity -JDBC Part-1

Type -1Driver

Type -1Driver

JDBC CallsODBCDriverODBCDriver

ODBC CallsType -1Driver

ODBCDriver

Translates all JDBC Calls intoODBC calls

DBMSDBMS

Page 24: Java DataBase Connectivity -JDBC Part-1

• 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

Page 25: Java DataBase Connectivity -JDBC Part-1

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.

Page 26: Java DataBase Connectivity -JDBC Part-1

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.

Page 27: Java DataBase Connectivity -JDBC Part-1

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

Page 28: Java DataBase Connectivity -JDBC Part-1

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)

Page 29: Java DataBase Connectivity -JDBC Part-1

• 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.

Page 30: Java DataBase Connectivity -JDBC Part-1

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.

Page 31: Java DataBase Connectivity -JDBC Part-1

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

Page 32: Java DataBase Connectivity -JDBC Part-1

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.

Page 33: Java DataBase Connectivity -JDBC Part-1

Type – 3Driver

Type – 3Driver

JDBC api callsDBMS – Independent

Net ProtocolsDBMS – Independent

Net Protocols

Translates

Server( Middleware Component )

DBMSDBMS Translated into DBMS Protocol

Page 34: Java DataBase Connectivity -JDBC Part-1

Java Application

JDBC API

Type - 3 Driver

Or ServerOr Server

net Common Protocolnet Common Protocol

MiddlewareComponent

Data

Or ServerOr Server

Page 35: Java DataBase Connectivity -JDBC Part-1

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

Page 36: Java DataBase Connectivity -JDBC Part-1

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.

Page 37: Java DataBase Connectivity -JDBC Part-1

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

Page 38: Java DataBase Connectivity -JDBC Part-1

Java Application

JDBC API

Thin, Type - 4 DriverNative protocolNative protocol

Uses Networking librariesUses Networking libraries

Thin, Type - 4 Driver

Data

Native protocolNative protocol

Page 39: Java DataBase Connectivity -JDBC Part-1

• 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.

Page 40: Java DataBase Connectivity -JDBC Part-1

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

Page 41: Java DataBase Connectivity -JDBC Part-1

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.

Page 42: Java DataBase Connectivity -JDBC Part-1

3. Seven Basic steps of using JDBC3. Seven Basic steps of using JDBC

42

Page 43: Java DataBase Connectivity -JDBC Part-1

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

Page 44: Java DataBase Connectivity -JDBC Part-1

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

Page 45: Java DataBase Connectivity -JDBC Part-1

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);

Page 46: Java DataBase Connectivity -JDBC Part-1

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

Page 47: Java DataBase Connectivity -JDBC Part-1

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);

}

Page 48: Java DataBase Connectivity -JDBC Part-1

Define the connection URLDefine the connection URLDefine the connection URLDefine the connection URL22

StringString msAccessURL = “jdbc:odbc:datasource”;

Page 49: Java DataBase Connectivity -JDBC Part-1

• 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);

Page 50: Java DataBase Connectivity -JDBC Part-1

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);

Page 51: Java DataBase Connectivity -JDBC Part-1

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

}

Page 52: Java DataBase Connectivity -JDBC Part-1

con.closecon.close();();

Close the connectionClose the connectionClose the connectionClose the connection77

Page 53: Java DataBase Connectivity -JDBC Part-1

Example 1Example 1

53

Page 54: Java DataBase Connectivity -JDBC Part-1

Example2

54

Page 55: Java DataBase Connectivity -JDBC Part-1

55

Page 56: Java DataBase Connectivity -JDBC Part-1

Example3

56

Page 57: Java DataBase Connectivity -JDBC Part-1

Example4

57

Page 58: Java DataBase Connectivity -JDBC Part-1

58

Page 59: Java DataBase Connectivity -JDBC Part-1

Thank You!Thank You!Thank You!Thank You!