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