SlideShare a Scribd company logo
PREPARED BY:
• NITESH KUKREJA
• POOJA TALREJA
What is JDBC?
• JDBC is Java application programming interface that
allows the Java programmers to access database
management system from the java code.
• It was developed by JavaSoft, a subsidiary of Sun
Microsystems.
• It is a java API which enables the java programs to
execute SQL statements.
Job of JDBC
• JDBC provides methods for querying and
updating the data in Relational Database
Management system such as SQL, Oracle etc.
• Generally all Relational Database Management
System supports SQL and we all know that Java is
platform independent.
• So JDBC makes it possible to write a single
database application that can run on different
platforms and interact with different Database
Management Systems.
Components of JDBC
• 1. The JDBC API.
• 2. The JDBC Driver Manager.
• 3. The JDBC Test Suite.
• 4. The JDBC-ODBC Bridge.
JDBC API
• The JDBC API provides the facility for accessing the
relational database from the Java programming
language.
• The user not only execute the SQL statements, retrieve
results, and update the data but can also access it
anywhere within a network because of it's "Write
Once, Run Anywhere" (WORA) capabilities.
• Due to JDBC API technology, user can also access other
tabular data sources like spreadsheets or flat files even
in the a heterogeneous environment.
JDBC API(Cont.)
• JDBC application programming interface is a part
of the Java platform that have included Java SE
and Java EE in itself.
• The latest version of JDBC 4.0 application
programming interface is divided into two
packages.
i) java.sql.
ii) javax.sql.
• Java SE and Java EE platforms are included in
both the packages.
JDBC Driver Manager
• The JDBC Driver Manager is a very important
class that defines objects which connect Java
applications to a JDBC driver.
• Usually Driver Manager is the backbone of the
JDBC architecture.
• It's very simple and small that is used to
provide a means of managing the different
types of JDBC database driver running on an
application.
JDBC Driver Manager(Cont.)
• The main responsibility of JDBC database
driver is to load all the drivers found in the
system properly as well as to select the most
appropriate driver from opening a connection
to a database.
• The Driver Manager also helps to select the
most appropriate driver from the previously
loaded drivers when a new open database is
connected.
JDBC Test Suite
• The function of JDBC driver test suite is to
make ensure that the JDBC drivers will run
user's program or not .
• The test suite of JDBC application program
interface is very useful for testing a driver
based on JDBC technology during testing
period.
• It ensures the requirement of Java Platform
Enterprise Edition (J2EE).
ODBC
(Open Data Base Connectivity)
• Open DataBase Connectivity is similar to Java
Database Connectivity which is used for
accessing and managing database, but the
difference is that JDBC is designed specifically
for Java programs, whereas ODBC is not
depended upon any language.
JDBC-ODBC Bridge
• The JDBC-ODBC bridge, also known as JDBC type
1 driver is a database driver that utilize the ODBC
driver to connect the database.
• This driver translates JDBC method calls into
ODBC function calls.
• The Bridge implements Jdbc for any database for
which an Odbc driver is available.
• The Bridge is always implemented as the
sun.jdbc.odbc Java package and it contains a
native library used to access ODBC.
Now we can conclude this topic:
• This first two component of JDBC, the JDBC API
and the JDBC Driver Manager manages to
connect to the database and then build a java
program that utilizes SQL commands to
communicate with any RDBMS.
• On the other hand, the last two components are
used to communicate with ODBC or to test web
application in the specialized environment.
Architecture of JDBC
JDBC Driver
• A JDBC driver translates standard JDBC calls into a
network or database protocol OR into a database
library API call that facilitates communication with the
database.
• There are four distinct types of JDBC drivers.
1. JDBC-ODBC Bridge + ODBC Driver, also called as Type1
2. Native API , Pure/partly Java Driver, also called Type 2.
3. JDBC –Net Pure Java Driver, also called Type 3.
4. Native Protocol , Pure Java Driver, also called Type 4.
JDBC-ODBC Bridge
Functions of JDBC-ODBC Bridge
• Translates query obtained by JDBC into
corresponding ODBC query, which is then
handled by the ODBC driver.
• Sun provides a JDBC-ODBC Bridge driver.
sun.jdbc.odbc.JdbcOdbcDriver. This driver is
native code and not Java, and is closed source.
• Client -> JDBC Driver -> ODBC Driver -> Database
• There is some overhead associated with the
translation work to go from JDBC to ODBC.
Native-API Driver
Functions of Native-API Driver
• This type of driver converts JDBC calls into
calls to the client API
• Better performance than Type 1 since no jdbc
to odbc translation is needed.
• Client -> JDBC Driver -> Vendor Client DB
Library -> Database for that database.
Network-Protocol Driver
Functions of Network Protocol Driver
• Follows a three tier communication approach.
• Can interface to multiple databases - Not
vendor specific.
• The client driver to middleware
communication is database independent.
• Client -> JDBC Driver -> Middleware-Net
Server -> Any Database
Native-Protocol Driver
Functions of Native Protocol Driver
• It is entirely written in Java that communicate directly
with a vendor's database through socket connections.
No translation or middleware layers, are required,
improving performance.
• The driver converts JDBC calls into the vendor-specific
database protocol so that client applications can
communicate directly with the database server.
• Completely implemented in Java to achieve platform
independence.
• Client Machine -> Native protocol JDBC Driver ->
Database server
SQL Package
• Provides the API for accessing and processing data stored in
a data source (usually a relational database) using the
Java programming language.
• This API includes a framework whereby different drivers
can be installed dynamically to access different data
sources.
• Although the JDBCTM API is mainly geared to passing SQL
statements to a database, it provides for reading and
writing data from any data source with a tabular format.
• The reader/writer facility, available through
the javax.sql.RowSet group of interfaces, can be customized
to use and update data from a spread sheet, or any other
tabular data source.
CONTENTS OF SQL PACKAGE
• The java.sql package contains API for the following:
1. Making a connection with a database via the
DriverManager facility
Class or Interface Purpose
DriverManager class makes a connection with a driver
SQLPermission class provides permission when code running
within a Security Manager, such as an
applet, attempts to set up a logging stream
through the DriverManager
Driver interface provides the API for registering and
connecting drivers based on JDBC
technology ("JDBC drivers"); generally used
only by the DriverManager class
DriverPropertyInfo class provides properties for a JDBC driver; not
used by the general user
Cont..
2. Sending SQL statements to a database
3. Retrieving and updating the results of a query
• ResultSet interface
Class or Interface Purpose
Statement class used to send basic SQL statements
PreparedStatement class used to send prepared statements or basic
SQL statements (derived from Statement)
CallableStatement class used to call database stored procedures
(derived from PreparedStatement)
Connection interface provides methods for creating statements
and managing connections and their
properties
Savepoint provides savepoints in a transaction
Cont..
4. Standard mappings for SQL types to classes and interfaces in the
Java programming language
Class or Interface Purpose
Array interface mapping for SQL ARRAY
Blob interface mapping for SQL BLOB
Clob interface mapping for SQL CLOB
NClob interface mapping for SQL NCLOB
Date class mapping for SQL DATE
Ref interface mapping for SQL REF
RowId interface mapping for SQL ROWID
Struct interface mapping for SQL STRUCT
SQLXML interface mapping for SQL XML
Time class mapping for SQL TIME
Timestamp class mapping for SQL TIMESTAMP
Types class provides constants for SQL types
Cont..
5. Custom mapping an SQL user-defined type (UDT) to a class in the Java
programming language
Class or Interface Purpose
SQLData interface specifies the mapping of a UDT to an
instance of this class
SQLInput interface provides methods for reading UDT
attributes from a stream
SQLOutput interface provides methods for writing UDT
attributes back to a stream
6. Metadata
Class or Interface Purpose
DatabaseMetaData interface provides information about the database
ResultSetMetaData interface provides information about the columns
of a ResultSet object
ParameterMetaData interface provides information about the
parameters to
PreparedStatement commands
Cont..
7. Exceptions
Exception Reason
SQLException thrown by most methods when there is a
problem accessing data and by some
methods for other reasons
SQLWarning thrown to indicate a warning
DataTruncation thrown to indicate that data may have
been truncated
BatchUpdateException thrown to indicate that not all commands
in a batch update executed successfully
JDBC DATA TYPES
JDBC TYPE JAVA TYPE
BIT boolean
TINY INT byte
SMALL INT short
INTEGER int
BIG INT long
REAL Float
FLOAT
DOUBLE
Double
BINARY
VARBINARY
LONGVARBINARY
byte[]
CHAR
VARCHAR
LONGVARCHAR
String
JDBC TYPE JAVA TYPE
NUMERIC
DECIMAL
BigDecimal
DATE java.sql.Date
TIME
TIMESTAMP
java.sql.Timestamp
CLOB Clob
BLOB Blob
ARRAY Array
DISTINCT Mapping of
underlying type
STRUCT Struct
REF Ref
JAVA_OBJECT Underlying java
class
SEVEN BASIC STEPS IN ESTABLISHING
CONNECTION WITH DATABASE
1. Load the driver.
2. Define the Connection URL.
3. Establish the Connection.
4. Create a Statement object.
5. Execute a Query.
6. Process the results.
7. Close the connection.
STEP 1-LOAD THE DRIVER
Not required in Java 6
• In Java SE 6.0 and later(Java 4.0 and later), the driver is loaded
automatically.
In Java 7,
For this step, DriverManager class is required.
• The DriverManager class maintains the list of the Driver classes.
Each driver has to be get
• registered in the DriverManager class by calling the method
DriverManager.registerDriver().
• By calling the Class.forName() method the driver class get
automatically loaded.
Syntax of Class.forName() method:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
DriverManager Class
Following are the methods of DriverManager class:
1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered
in the DriverManager class.
2. registerDriver(Driver driver) : It registers the driver with the DriverManager class.
3. getConnection(String url) : It tries to establish the connection to a given database
URL.
4. getConnection(String url, String user, String password) : It tries to establish the
connection to a given database URL.
5. getConnection(String url, Properties info) : It tries to establish the connection to a
given database URL.
6. getDriver(String url) : It attempts to locate the driver by the given string.
7. getDrivers() : It retrieves the enumeration of the drivers which has been registered
with the DriverManager class.
STEP 2-DEFINE THE CONNECTION URL
• This URL has three parts:
“jdbc:odbc:MyDataSource”
<Protocol><subprotocol>MyDataSource<subname>
<protocol> in a JDBC URL is always jdbc
<subprotocol> is the name of the database connectivity mechanism. If
the mechanism to retrieve the data is an ODBC -JDBC bridge. The
sub protocol is odbc
<subname> is used to identify the database.
Data Source
Data Source is the source to which the connection is
to be established. It can be in MySQL, MS Access, etc.
Before establishing the connection, we need to
configure the data source so that we can use it in our
java application. Following are the steps for creating a
data source:
Step 1- GoTo Control Panel -> System and Security->Administrative tools.
Click on Data Sources(ODBC)
Step 2- A window will appear like this, User DSN tab appears
by default. Click on System DSN tab.
Step 3- In System DSN, click on Add button
Step 4- In this window, select the type of driver as per the database. For
MS Access select the Driver do Microsoft Access(*.mdb)
Step 5- Now, in this give a name to your DSN and specify the
path of your mdb file by clicking on Select button and click on
OK.
Step 6- Now, your data source will be added in the list.
Step 3 – ESTABLISH THE CONNECTION
A Connection object represents a connection with a database.
When we connect to a database by using connection method, we create
a Connection Object, which represents the connection to the database.
An application may have one or more than one connections with a
single database or many connections with the different databases also.
In the first step we have loaded the database driver to be used. Now its
time to make the connection with the database server. Following code
we have used to make the connection with the database:
Syntax :
Connection conobj = DriverManager.getConnection(String url);
Where, conobj – is the object of connection Class that represent a
connection between the database and the client
url – is the connection url.
Step 4- Create a Statement object
Idea:
• Once a connection is obtained we can interact with the database. The
JDBC Statement, CallableStatement, and PreparedStatement interfaces
define the methods and properties that enable you to send SQL or
PL/SQL commands and receive data from your database.
• They also define methods that help bridge data type differences
between Java and SQL data types used in a database.
Types of Statements:
• Statement – eg. Select statement
• PreparedStatement – eg. Insert, Update, Delete, etc
• CallableStatement - eg. Stored procedures and functions
Example:
Statement s=con.createStatement();
Step 5 – Execute a Query
• The executeQuery() method of Statement interface is used to execute
queries to the database.
• This method returns the object of ResultSet that can be used to get all
the records of a table.
• Syntax:
public ResultSet executeQuery(String sql)throws SQLException
• Example:
ResultSet rs=stm.executeQuery(“Select * from student”);
• The executeUpdate() method of Statement interface is used to execute
queries to the database.
• It is used to insert, delete, and update the database
• Syntax:
int executeUpdate(String sql)throws SQLException
• Example:
int i=stm.executeUpdate(“insert into student values(11,’name’)”);
Step 6 – Process the Result
In this step we receives the result of execute statement. In this case we
will fetch the employees records from the recordset object and show on
the command prompt. Here is the code:
// 0 1
//name rollno
while (res.next())
{
String studName = res.getString( “student_name " );
//String studName = res.getString( 0); // index of column
System.out.println( studName );
int roll = res.getInt(1);
int roll = res.getInt(“roll_no”);
System.out.println( +roll );
}
Step 7 – Close the connection
• By closing connection object Statement and ResultSet will
be closed automatically. The close() method of Connection
interface is used to close the connection.
• Syntax:
public void close()throws SQLException
• Example:
con.close();
Java Database Connectivity (JDBC)

More Related Content

What's hot (20)

PPT
Jdbc complete
Sandeep Rawat
 
PPTX
C# Tutorial
Jm Ramos
 
PDF
Introduction to ASP.NET Core
Avanade Nederland
 
PPTX
Java database connectivity with MySql
Dhyey Dattani
 
PPTX
Reactjs
Mallikarjuna G D
 
PPTX
Node.js Express
Eyal Vardi
 
PDF
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
PPTX
Object Oriented Programming
Iqra khalil
 
PPTX
Introduction to React JS for beginners
Varun Raj
 
PDF
Expressjs
Yauheni Nikanovich
 
PPTX
ASP.NET Web API
habib_786
 
PPT
Tomcat
Venkat Pinagadi
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PPT
Asp.net basic
Neelesh Shukla
 
PPTX
Node js
Fatih Şimşek
 
PPTX
The Benefits of Using React JS for Web Development!
Baharika Sopori
 
PPTX
React js
Oswald Campesato
 
PPT
Introduction to the Web API
Brad Genereaux
 
Jdbc complete
Sandeep Rawat
 
C# Tutorial
Jm Ramos
 
Introduction to ASP.NET Core
Avanade Nederland
 
Java database connectivity with MySql
Dhyey Dattani
 
Node.js Express
Eyal Vardi
 
Model View Controller (MVC)
Javier Antonio Humarán Peñuñuri
 
Object Oriented Programming
Iqra khalil
 
Introduction to React JS for beginners
Varun Raj
 
ASP.NET Web API
habib_786
 
Introduction to Spring Framework
Serhat Can
 
Asp.net basic
Neelesh Shukla
 
The Benefits of Using React JS for Web Development!
Baharika Sopori
 
Introduction to the Web API
Brad Genereaux
 

Viewers also liked (20)

PPT
Virtuoso ODBC Driver Configuration & Usage (Windows)
Kingsley Uyi Idehen
 
PPT
Java presentation
Karan Sareen
 
KEY
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
PPS
Jdbc example program with access and MySql
kamal kotecha
 
PPTX
JDBC ppt
Rohit Jain
 
PPTX
Database Access With JDBC
Dharani Kumar Madduri
 
PPT
Jdbc ppt
Vikas Jagtap
 
PPT
Mobile Bootcamp Presentation: Mobile Application Development Platforms
Wilfred Mutua Mworia
 
PPTX
Jdbc in servlets
Nuha Noor
 
PPT
Java Presentation
pm2214
 
PPT
JDBC Java Database Connectivity
Ranjan Kumar
 
PPS
Jdbc architecture and driver types ppt
kamal kotecha
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PPTX
Android vs iOS
Manan Narang
 
PPT
Java basic
Sonam Sharma
 
PPTX
Introduction to java
Veerabadra Badra
 
Virtuoso ODBC Driver Configuration & Usage (Windows)
Kingsley Uyi Idehen
 
Java presentation
Karan Sareen
 
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Jdbc example program with access and MySql
kamal kotecha
 
JDBC ppt
Rohit Jain
 
Database Access With JDBC
Dharani Kumar Madduri
 
Jdbc ppt
Vikas Jagtap
 
Mobile Bootcamp Presentation: Mobile Application Development Platforms
Wilfred Mutua Mworia
 
Jdbc in servlets
Nuha Noor
 
Java Presentation
pm2214
 
JDBC Java Database Connectivity
Ranjan Kumar
 
Jdbc architecture and driver types ppt
kamal kotecha
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
Android vs iOS
Manan Narang
 
Java basic
Sonam Sharma
 
Introduction to java
Veerabadra Badra
 
Ad

Similar to Java Database Connectivity (JDBC) (20)

PPTX
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
DOC
jdbc document
Yamuna Devi
 
PPTX
java.pptx
bfgd1
 
PDF
Jdbc 1
Mukesh Tekwani
 
PPT
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
PPTX
Chapter_4_-_JDBC[1].pptx
BachaSirata
 
PPTX
Jdbc introduction
Rakesh Kumar Ray
 
PPTX
Core jdbc basics
Sourabrata Mukherjee
 
PPT
JDBC.ppt
ChagantiSahith
 
PPT
Java database connectivity
Vaishali Modi
 
PPT
Java database connectivity
Vaishali Modi
 
PPT
JDBC java for learning java for learn.ppt
kingkolju
 
PPTX
Java database connectivity with MySql
Dhyey Dattani
 
PDF
JDBC with MySQL.pdf
Arumugam90
 
PDF
JDBC with MySQL.pdf
Arumugam90
 
PPT
java database connection (jdbc)
Sanjay Gunjal
 
PPT
jdbc
Gayatri Patel
 
PPTX
Advanced JAVA
Rajvi Vaghasiya
 
PDF
Java Database Connectivity (Advanced programming)
Gera Paulos
 
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
jdbc document
Yamuna Devi
 
java.pptx
bfgd1
 
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
Chapter_4_-_JDBC[1].pptx
BachaSirata
 
Jdbc introduction
Rakesh Kumar Ray
 
Core jdbc basics
Sourabrata Mukherjee
 
JDBC.ppt
ChagantiSahith
 
Java database connectivity
Vaishali Modi
 
Java database connectivity
Vaishali Modi
 
JDBC java for learning java for learn.ppt
kingkolju
 
Java database connectivity with MySql
Dhyey Dattani
 
JDBC with MySQL.pdf
Arumugam90
 
JDBC with MySQL.pdf
Arumugam90
 
java database connection (jdbc)
Sanjay Gunjal
 
Advanced JAVA
Rajvi Vaghasiya
 
Java Database Connectivity (Advanced programming)
Gera Paulos
 
Ad

Recently uploaded (20)

PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 

Java Database Connectivity (JDBC)

  • 1. PREPARED BY: • NITESH KUKREJA • POOJA TALREJA
  • 2. What is JDBC? • JDBC is Java application programming interface that allows the Java programmers to access database management system from the java code. • It was developed by JavaSoft, a subsidiary of Sun Microsystems. • It is a java API which enables the java programs to execute SQL statements.
  • 3. Job of JDBC • JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. • Generally all Relational Database Management System supports SQL and we all know that Java is platform independent. • So JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
  • 4. Components of JDBC • 1. The JDBC API. • 2. The JDBC Driver Manager. • 3. The JDBC Test Suite. • 4. The JDBC-ODBC Bridge.
  • 5. JDBC API • The JDBC API provides the facility for accessing the relational database from the Java programming language. • The user not only execute the SQL statements, retrieve results, and update the data but can also access it anywhere within a network because of it's "Write Once, Run Anywhere" (WORA) capabilities. • Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files even in the a heterogeneous environment.
  • 6. JDBC API(Cont.) • JDBC application programming interface is a part of the Java platform that have included Java SE and Java EE in itself. • The latest version of JDBC 4.0 application programming interface is divided into two packages. i) java.sql. ii) javax.sql. • Java SE and Java EE platforms are included in both the packages.
  • 7. JDBC Driver Manager • The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. • Usually Driver Manager is the backbone of the JDBC architecture. • It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application.
  • 8. JDBC Driver Manager(Cont.) • The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. • The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected.
  • 9. JDBC Test Suite • The function of JDBC driver test suite is to make ensure that the JDBC drivers will run user's program or not . • The test suite of JDBC application program interface is very useful for testing a driver based on JDBC technology during testing period. • It ensures the requirement of Java Platform Enterprise Edition (J2EE).
  • 10. ODBC (Open Data Base Connectivity) • Open DataBase Connectivity is similar to Java Database Connectivity which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
  • 11. JDBC-ODBC Bridge • The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database driver that utilize the ODBC driver to connect the database. • This driver translates JDBC method calls into ODBC function calls. • The Bridge implements Jdbc for any database for which an Odbc driver is available. • The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native library used to access ODBC.
  • 12. Now we can conclude this topic: • This first two component of JDBC, the JDBC API and the JDBC Driver Manager manages to connect to the database and then build a java program that utilizes SQL commands to communicate with any RDBMS. • On the other hand, the last two components are used to communicate with ODBC or to test web application in the specialized environment.
  • 14. JDBC Driver • A JDBC driver translates standard JDBC calls into a network or database protocol OR into a database library API call that facilitates communication with the database. • There are four distinct types of JDBC drivers. 1. JDBC-ODBC Bridge + ODBC Driver, also called as Type1 2. Native API , Pure/partly Java Driver, also called Type 2. 3. JDBC –Net Pure Java Driver, also called Type 3. 4. Native Protocol , Pure Java Driver, also called Type 4.
  • 16. Functions of JDBC-ODBC Bridge • Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. • Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source. • Client -> JDBC Driver -> ODBC Driver -> Database • There is some overhead associated with the translation work to go from JDBC to ODBC.
  • 18. Functions of Native-API Driver • This type of driver converts JDBC calls into calls to the client API • Better performance than Type 1 since no jdbc to odbc translation is needed. • Client -> JDBC Driver -> Vendor Client DB Library -> Database for that database.
  • 20. Functions of Network Protocol Driver • Follows a three tier communication approach. • Can interface to multiple databases - Not vendor specific. • The client driver to middleware communication is database independent. • Client -> JDBC Driver -> Middleware-Net Server -> Any Database
  • 22. Functions of Native Protocol Driver • It is entirely written in Java that communicate directly with a vendor's database through socket connections. No translation or middleware layers, are required, improving performance. • The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server. • Completely implemented in Java to achieve platform independence. • Client Machine -> Native protocol JDBC Driver -> Database server
  • 23. SQL Package • Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language. • This API includes a framework whereby different drivers can be installed dynamically to access different data sources. • Although the JDBCTM API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. • The reader/writer facility, available through the javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, or any other tabular data source.
  • 24. CONTENTS OF SQL PACKAGE • The java.sql package contains API for the following: 1. Making a connection with a database via the DriverManager facility Class or Interface Purpose DriverManager class makes a connection with a driver SQLPermission class provides permission when code running within a Security Manager, such as an applet, attempts to set up a logging stream through the DriverManager Driver interface provides the API for registering and connecting drivers based on JDBC technology ("JDBC drivers"); generally used only by the DriverManager class DriverPropertyInfo class provides properties for a JDBC driver; not used by the general user
  • 25. Cont.. 2. Sending SQL statements to a database 3. Retrieving and updating the results of a query • ResultSet interface Class or Interface Purpose Statement class used to send basic SQL statements PreparedStatement class used to send prepared statements or basic SQL statements (derived from Statement) CallableStatement class used to call database stored procedures (derived from PreparedStatement) Connection interface provides methods for creating statements and managing connections and their properties Savepoint provides savepoints in a transaction
  • 26. Cont.. 4. Standard mappings for SQL types to classes and interfaces in the Java programming language Class or Interface Purpose Array interface mapping for SQL ARRAY Blob interface mapping for SQL BLOB Clob interface mapping for SQL CLOB NClob interface mapping for SQL NCLOB Date class mapping for SQL DATE Ref interface mapping for SQL REF RowId interface mapping for SQL ROWID Struct interface mapping for SQL STRUCT SQLXML interface mapping for SQL XML Time class mapping for SQL TIME Timestamp class mapping for SQL TIMESTAMP Types class provides constants for SQL types
  • 27. Cont.. 5. Custom mapping an SQL user-defined type (UDT) to a class in the Java programming language Class or Interface Purpose SQLData interface specifies the mapping of a UDT to an instance of this class SQLInput interface provides methods for reading UDT attributes from a stream SQLOutput interface provides methods for writing UDT attributes back to a stream 6. Metadata Class or Interface Purpose DatabaseMetaData interface provides information about the database ResultSetMetaData interface provides information about the columns of a ResultSet object ParameterMetaData interface provides information about the parameters to PreparedStatement commands
  • 28. Cont.. 7. Exceptions Exception Reason SQLException thrown by most methods when there is a problem accessing data and by some methods for other reasons SQLWarning thrown to indicate a warning DataTruncation thrown to indicate that data may have been truncated BatchUpdateException thrown to indicate that not all commands in a batch update executed successfully
  • 29. JDBC DATA TYPES JDBC TYPE JAVA TYPE BIT boolean TINY INT byte SMALL INT short INTEGER int BIG INT long REAL Float FLOAT DOUBLE Double BINARY VARBINARY LONGVARBINARY byte[] CHAR VARCHAR LONGVARCHAR String JDBC TYPE JAVA TYPE NUMERIC DECIMAL BigDecimal DATE java.sql.Date TIME TIMESTAMP java.sql.Timestamp CLOB Clob BLOB Blob ARRAY Array DISTINCT Mapping of underlying type STRUCT Struct REF Ref JAVA_OBJECT Underlying java class
  • 30. SEVEN BASIC STEPS IN ESTABLISHING CONNECTION WITH DATABASE 1. Load the driver. 2. Define the Connection URL. 3. Establish the Connection. 4. Create a Statement object. 5. Execute a Query. 6. Process the results. 7. Close the connection.
  • 31. STEP 1-LOAD THE DRIVER Not required in Java 6 • In Java SE 6.0 and later(Java 4.0 and later), the driver is loaded automatically. In Java 7, For this step, DriverManager class is required. • The DriverManager class maintains the list of the Driver classes. Each driver has to be get • registered in the DriverManager class by calling the method DriverManager.registerDriver(). • By calling the Class.forName() method the driver class get automatically loaded. Syntax of Class.forName() method: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
  • 32. DriverManager Class Following are the methods of DriverManager class: 1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class. 2. registerDriver(Driver driver) : It registers the driver with the DriverManager class. 3. getConnection(String url) : It tries to establish the connection to a given database URL. 4. getConnection(String url, String user, String password) : It tries to establish the connection to a given database URL. 5. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL. 6. getDriver(String url) : It attempts to locate the driver by the given string. 7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class.
  • 33. STEP 2-DEFINE THE CONNECTION URL • This URL has three parts: “jdbc:odbc:MyDataSource” <Protocol><subprotocol>MyDataSource<subname> <protocol> in a JDBC URL is always jdbc <subprotocol> is the name of the database connectivity mechanism. If the mechanism to retrieve the data is an ODBC -JDBC bridge. The sub protocol is odbc <subname> is used to identify the database.
  • 34. Data Source Data Source is the source to which the connection is to be established. It can be in MySQL, MS Access, etc. Before establishing the connection, we need to configure the data source so that we can use it in our java application. Following are the steps for creating a data source:
  • 35. Step 1- GoTo Control Panel -> System and Security->Administrative tools. Click on Data Sources(ODBC)
  • 36. Step 2- A window will appear like this, User DSN tab appears by default. Click on System DSN tab.
  • 37. Step 3- In System DSN, click on Add button
  • 38. Step 4- In this window, select the type of driver as per the database. For MS Access select the Driver do Microsoft Access(*.mdb)
  • 39. Step 5- Now, in this give a name to your DSN and specify the path of your mdb file by clicking on Select button and click on OK.
  • 40. Step 6- Now, your data source will be added in the list.
  • 41. Step 3 – ESTABLISH THE CONNECTION A Connection object represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database. An application may have one or more than one connections with a single database or many connections with the different databases also. In the first step we have loaded the database driver to be used. Now its time to make the connection with the database server. Following code we have used to make the connection with the database: Syntax : Connection conobj = DriverManager.getConnection(String url); Where, conobj – is the object of connection Class that represent a connection between the database and the client url – is the connection url.
  • 42. Step 4- Create a Statement object Idea: • Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. • They also define methods that help bridge data type differences between Java and SQL data types used in a database. Types of Statements: • Statement – eg. Select statement • PreparedStatement – eg. Insert, Update, Delete, etc • CallableStatement - eg. Stored procedures and functions Example: Statement s=con.createStatement();
  • 43. Step 5 – Execute a Query • The executeQuery() method of Statement interface is used to execute queries to the database. • This method returns the object of ResultSet that can be used to get all the records of a table. • Syntax: public ResultSet executeQuery(String sql)throws SQLException • Example: ResultSet rs=stm.executeQuery(“Select * from student”); • The executeUpdate() method of Statement interface is used to execute queries to the database. • It is used to insert, delete, and update the database • Syntax: int executeUpdate(String sql)throws SQLException • Example: int i=stm.executeUpdate(“insert into student values(11,’name’)”);
  • 44. Step 6 – Process the Result In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the command prompt. Here is the code: // 0 1 //name rollno while (res.next()) { String studName = res.getString( “student_name " ); //String studName = res.getString( 0); // index of column System.out.println( studName ); int roll = res.getInt(1); int roll = res.getInt(“roll_no”); System.out.println( +roll ); }
  • 45. Step 7 – Close the connection • By closing connection object Statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. • Syntax: public void close()throws SQLException • Example: con.close();