Unit 1: JDBC (Java Database Connectivity)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Unit 1: JDBC (Java Database Connectivity)

JDBC is a standard Java API for a database-independent connectivity between the Java
programming language and a wide range of databases. This application program interface lets
you encode the access request statements, in Structured Query Language (SQL). They are
then passed to the program that manages the database. It mainly involves opening a
connection, creating a SQL Database, executing SQL queries and then arriving at the output.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the databases.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The driver manager is capable of supporting
multiple concurrent drivers connected to multiple heterogeneous databases.

Common JDBC Components


The JDBC API provides the following interfaces and classes −

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 1


DriverManager is used to manage a list of database drivers. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database Connection.
Driver is an interface that handles the communications with the database server. It also
abstracts the details associated with working with Driver objects.
Connection is an interface that consists all the methods required to connect to a database. The
connection object represents communication context, i.e., all communication with the
database is through connection object only.

JDBC Driver Types


JDBC drivers are used to implement the defined interfaces in the JDBC API, for interacting
with the database server. A JDBC driver does three things and they are as follows:
1. Establishes a connection with a data source.
2. It will send queries and update statements to the data source.
3. Finally, it processes the results.
There are 4 types of drivers, namely:
Type 1: JDBC-ODBC Bridge Diver
In Type 1 driver, a JDBC bridge accesses ODBC drivers installed on each client machine.
Further, ODBC configures Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed
on each client machine.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 2


The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3: JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS and forwarded to the database server.

This kind of driver is extremely flexible since it requires no code installed on the client and a
single driver can actually provide access to multiple databases. You can think of the
application server as a JDBC “proxy,” meaning that it makes calls for the client application.
As a result, you need some knowledge of the application server’s configuration in order to
effectively use this driver type. Your application server might use a Type 1, 2, or 4 drivers to
communicate with the database.
Type 4: 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor’s
database through a socket connection. This is the highest performance driver available for the
database and is usually provided by the vendor itself.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 3


This kind of driver is extremely flexible, you don’t have to install special software on the
client or server. Further, these drivers can be downloaded dynamically.
MySQL’s Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Steps to create JDBC Application


In order to create JDBC Application, we need to follow few steps.

1) Import the packages:


You need to include the packages containing the JDBC classes needed for database
programming. Most often, using import java.sql.* will suffice.
2) Register the JDBC driver:
Here you have to initialize a driver so that you can open a communication channel with the
database.
3) Open a connection:
Here, you can use the getConnection() method to create a Connection object, which
represents a physical connection with the database.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 4


4) Execute a query:
Requires using an object of type Statement for building and submitting an SQL statement to
the database.
Extract data from result set: Requires that you use the appropriate getXXX() method to
retrieve the data from the result set.
5) Clean up the environment:
Requires explicitly closing all database resources versus relying on the JVM’s garbage
collection.
Statement, PreparedStatement & CallableStatement in Java:
JDBC API provides 3 different interfaces to execute the different types of SQL queries. They
are,
1) Statement
Statement interface is used to execute normal SQL queries. You can’t pass the parameters
to SQL query at run time using this interface

Example:

//Creating The Statement Object

Statement stmt = con.createStatement();

//Executing The Statement

stmt.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME


VARCHAR)");

2) PreparedStatement
PreparedStatement is used to execute dynamic or parameterized SQL queries.
PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface
//Creating PreparedStatement object
PreparedStatement pstmt = con.prepareStatement("update STUDENT set NAME = ? where
ID = ?");
//Setting values to place holders using setter methods of PreparedStatement object
pstmt.setString(1, "MyName"); //Assigns "MyName" to first place holder
pstmt.setInt(2, 111); //Assigns "111" to second place holder
//Executing PreparedStatement
pstmt.executeUpdate();
3) CallableStatement

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 5


CallableStatement is used to execute the stored procedures. CallableStatement extends
PreparedStatement. Usng CallableStatement, you can pass 3 types of parameters to stored
procedures. They are : IN – used to pass the values to stored procedure, OUT – used to hold
the result returned by the stored procedure and IN OUT – acts as both IN and OUT
parameter.
//Creating CallableStatement object
CallableStatement cstmt = con.prepareCall("{call anyProcedure(?, ?, ?)}");
//Use cstmt.setter() methods to pass IN parameters
//Use cstmt.registerOutParameter() method to register OUT parameters
//Executing the CallableStatement
cstmt.execute();
//Use cstmt.getter() methods to retrieve the result returned by the stored procedure

Statement Vs PreparedStatement Vs CallableStatement In Java:

ResultSet
A ResultSet is a Java object that contains the results of executing an SQL query. In other
words, it contains the rows that satisfy the conditions of the query. The data stored in a
ResultSet object is retrieved through a set of get methods that allows access to the various

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 6


columns of the current row. The ResultSet.next method is used to move to the next row of the
ResultSet, making it the current row.

The general form of a result set is a table with column headings and the corresponding values
returned by a query.
Commonly used methods of ResultSet interface

1) public boolean next():


is used to move the cursor to the one row next from the current position.
2) public boolean previous():
is used to move the cursor to the one row previous from the current position.
3) public boolean first():
is used to move the cursor to the first row in result set object.
4) public boolean last():
is used to move the cursor to the last row in result set object.

PROF. BHUSHAN L RATHI (GHRIBM,JALGAON) 7

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy