Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

JDBC is a phrase that is used to specify Java Database Connectivity.

It is an interface with the Java Application Program known as


Application Programming Interface (API) on one end and the data set
defined as a database on another end.

JAVA API JDBC


Database

It is used to link an application written in Java language in any


platform, that is, operating systems such as Windows, Unix and
Fedora, and many others with Database as backend.
•JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server.
•For example, JDBC drivers enable you to open database connections
and to interact with it by sending SQL or database commands then
receiving results with Java.
•The Java.sql package that ships with JDK, contains various classes
with their behaviours defined and their actual implementaions are
done in third-party drivers.
• Third party vendors implements the java.sql.Driver interface in their
database driver.
This backend can be any database like MS Access, Oracle, ‘My SQL’
and ‘SQL Server’.
It allows any java program to execute SQL (Structured Query
Language) statements and retrieve results, modify data and delete
data.
Different Java API’S that JDBC can link to Database are:
1.Core Java (Java Standard Edition or Java SE) supports: Java
Application and Java Applet
2.Advanced Java(Java Enterprise Edition or Java EE) supports:
Servlet ,Java Server Page (JSP) ,and Enterprise Java Bean (EJB).
JDBC Architecture
JDBC-API may be defined based on one-tier, two-tier, three-tier or N-
tier architectures depending upon the server (where database
generally resides) and the client programs.
1 tier architecture:
also known as single-tier architecture, is software architecture in
which all the required components for the working of application are
available under the same package.
2 tier architecture:
2 tier architecture is the one in which the user interface layer and the
database layer are located in two different machines. It means that
the client and the server are not on the same computer.
3 tier architecture:
Unlike 2 tier architecture, 2 servers perform the major tasks in this
application. One server is for the business layer and the other is the
database layer.
JDBC API: Gives a strong link between the Java Application and the
JDBC.
JDBC Driver API: Gives the connectivity between JDBC and the Driver.

Java JDBC API JDBC JDBC


Driver
Application Driver API
•The drivers are previously installed in the computer for providing link
to the different databases.
• The DriverManager class defines different drivers for multiple data
source.
•The driver manager supports many simultaneous drivers connected
to different assorted databases.
Core Components of JDBC
DriverManager:
• Class resides under java.sql package and is defined as the primary
component of JDBC.
•DriverManager
organizes the database drivers,
 loads all the drivers of different databases
 selection of suitable database driver
when a new connection is recognized.
Different Types of JDBC Drivers
JDBC driver implementations vary because of
1. the wide variety of operating systems
2. hardware platforms in which Java operates.
Sun has divided the implementation types into four categories:
• Types 1, 2, 3, and 4,
Type 1: JDBC-ODBC Bridge Driver :
•In this driver, the JDBC bridge is
created to access ODBC drivers CLIENT MACHINE SERVER MACHINE
installed on different client machines. JDBC-ODBC
•The configuration of Data Source BRIDGE DRIVER

Name (DSN) in the system defines the


target database by means of ODBC. ODBC DRIVER
DATABASE
SERVER
• it receives any JDBC calls and sends
them to ODBC(Open Database VENDOR DB
Connectivity) driver. LIBRARY

•ODBC driver understands these calls


and communicates with database
library provided by vendor.
Type 2: JDBC-Native API :
•In a Type 2 driver, It converts JDBC calls
into database-specific calls with the help of
vendor Database Library.
•It communicates directly with database
server therefore requires that some binary
code be present on client machine. CLIENT MACHINE SERVER MACHINE
Native API-
Partly Java
Driver

DATABASE
SERVER

VENDOR DB
LIBRARY
Type 3: JDBC-Net pure Java
•In a Type 3 driver, a three-tier approach is CLIENT SERVER DATABASE

used to access databases. MACHINE MACHINE MACHINE

•JDBC database requests are passed through Net-


Middle
the network to a middle tier Server (ex. Net
Protocol Database
ware
Pure Java server
server

Server)
Driver

•Middle Tier server translates the request to


database specific library and then snds it to
database server.
•Database server then executes the request
and gives back result.
Type 4: 100% Pure Java
•This Driver converts JDBC calls into Vendor
specific (DBMS)protocol so that client
applications can communicate directly with CLIENT MACHINE SERVER MACHINE
database Server.
•Level 4 drivers are completely
implemented in Java to achieve platform Net-Protocol Pure
Java Driver
DATABASE
independence and eliminate deployment SERVER

administration issues.
•MySQL’s Connector/J driver is a Type 4
driver.
Which Driver Should be Used?
•If any one type of database is accessed, such as Oracle, SQL Server or
MYSQL, the preferred driver type is 4.
• If multiple types of databases are accessed at the same time by the
Java application, the Type 3 is the preferred driver.
•If Type 3 or Type 4 drivers are not available for the database then
Type 2 drivers are useful in this situation.
• The Type 1 driver is used for development and testing purposes only
since it is not considered as the deployment-level driver.
Connection:
Connection interface contains concept for the admission of recognition
with a database.
The DriverManager implements the Connection interface.
A Connection object is obtained using the getConnection() function
call.
Syntax:

Connection conn = DriverManager.getConnection(dburl, usrname, passwrd);


Statement :
•The Statement interface defines a generalized construct to run different SQL
statements.
•It implements ResultSet Object to show the resultant dataset
•Every object of the Statement interface consists of one ResultSet object.
•The execute() method in Statement closes its contemporary resultant data set if it is
previously opened.
•PreparedStatement interface and CallableStatement interface are two dedicated sub
interfaces of the Statement interface.
•A Statement object is created by using the createStatement() method

Statement stmt = conn.createStatement();


The statement can be executed for the retrieval of the dataset based on the ResultSet
using executeQuery(query); method
This can be repeated until and unless the End Of File (EOF) is encountered.

Emp Table

Above example selects all the tuples from the employee table defined as ‘EMP’.
res.next() method returns true until and unless it reaches the EOF and false otherwise.
PreparedStatement :
PreparedStatement remains under the Statement as a sub interface hierarchically.
It uses compilation before hand and hence execution procedure of the
PreparedStatement is comparably faster than the Statement interface, since, the
PreparedStatement is already prepared for execution.

PreparedStatement object is retrieved from the object of Connection using the following
method.
PreparedStatement has a set of setXX() functions too along with
parameters.

In setString() the index starts from 1 (means the first attribute) and not
0.
The setXX() methods, like setString(), setInt() should be called prior to
the calling of the executeUpdate() method.
CallableStatement :
It inherits the properties of the PreparedStatement and includes methods suitable for
procedure calls .

Hence CallableStatement is used to run SQL procedures.


CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.

Suppose you need to get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
The prepareCall() method of Connection interface returns the instance
of CallableStatement.
public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

example:
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
ResultSet :
•The ResultSet interface provides a data set in the form of a table.
• It is given as the output of the resultant data by implementing a SQL statement within
JDBC program.
•It defines an iterative process based on the “rs.next()” method returning false if the EOF
marker (End Of File marker) is reached.
RowId:
• Defines the memory location on which a row or dataset is stored.
•It returns the address of a row.
•It spots a row in a database uniquely.
•RowId is a built-in data type in JDBC particularly used during the
returning of the address of a row.
SQLException Methods:
A SQLException pops up when some conditional mismatch occurs either in the driver or
in the database itself.

If this type of exception pops up, an object of SQLException is cascaded as input to the
catch block.

The following methods are some basic common exceptions that are handled for getting
information for the thrown exception.
JDBC Data Types:
JDBC Example
A JDBC application should include the following steps:
1.Importing the different packages
2.Registration of the JDBC driver
3.Commence a connection
4.Generate a statement
5.Run a query
6.Take out required data based on the result set
7.Close result set, statement and connection (Data Cleaning)
MYSQL BASICS
One has to install MySql 5.7
MYSQL BASICS
Once installed open Mysql 5.7 Command Line Client

Show existing databases


Create Database and Create Table
Insert into tables and Select query
JDBC Example
A JDBC application should include the following steps:
1.Importing the different packages
2.Registration of the JDBC driver
3.Establish a connection
4.Generate a Sql statement
5.Run/Execute a statement containing query
6.Take out required data based on the result set
7.Close connection (Data Cleaning)
Output:
The JDBC driver is a collection of predefined Java classes enabling the communication
based on a defined database.

A driver is a hardware/software that makes two separate computing systems talk to


each other.

For instance, Oracle will have its own JDBC driver and MySQL another definitive JDBC
driver implementing enormous interfaces.
While using a given driver, it uses the model JDBC interface.
Consequently, we can generate a new JDBC driver considering the JDBC code as a black
box.

public static void forName(String className) throws ClassNotFoundException


After loading and initializing the said driver, we need the communication or link with the
database.
All such communications with the JAVA Application are established through the
Connection object.
Multiple connections can commence at a time for communicating with the same
database.
We can do that in two different ways.
1. Creating a DSN (Data Source Name) – This procedure is ideal since it provides
the detailed information of the data source to the respective Java application. It is better
compared to the ‘DriverManager’ class definition concept.

// Here dsn is the “Data Source Name” DSN stands for Data Source Name.

conn= DriverManager.getConnection(“jdbc:odbc:dsn”);
DSN Name:
creates a link between the JDBC driver and the ODBC driver (created to
connect Oracle/MySQL/SQLServer/MSAccess).
A DSN must be created prior to the execution of the program and
following are the steps for doing that in Windows versions.
The system may be a 32-bit processor or a 64-bit processor in Windows
platform.
1.Search for ODBC Data Sources app and click on one based on your
system’s processor (64 bit or 32 bit)resp.
2. Double click to open the following dialog box
3. Select “System DSN” tab. As a result, DSN can be created, connecting
databases with applications across other computer systems connected
in a network (LAN). This is very important for ‘Distributed Systems’.
4. For adding a new DSN, the ‘ADD’ button should be clicked. It opens
the following dialog showing all the drivers of different types of files
based on which a DSN can be created. Selecting a required driver, the
‘Finish’ button is clicked.
5. After clicking on the ‘Finish’ button the dialog ‘ODBC Microsoft
Access Setup’ is invoked.
6. After this ‘Select’ button should be clicked and necessary database
should be selected.
6. After this ‘Select’ button should be clicked and necessary database
should be selected.
6. Thus, the required DSN is created after clicking on ‘OK’ button.
[in our case Microsoft Access Database has been created. ]
6. Thus, the required DSN is created after clicking on ‘OK’ button.
[in our case Microsoft Access Database has been created. ]
Now you can write a program to retrieve data from MS Access database
INSERT BULK DATA Transection INTO THE TABLE USING PreparedStatement Interface
Output:
Thank You

You might also like