AJP - SESSION - 2 - JDBC Components - JDBC - Driver - Types

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

8CSPL6241-ADVANCED JAVA PROGRAMMING

Module 1

• Common JDBC Components:-


• Driver
• DriverManager
• Connection
• Steps to create JDBC Application
• JDBC Driver Types.

Prof. Mohan Reddy . Y


Assistant Professor, SOSS, CMR University

Session – 2
Thursday, 28th Jul 2022
10:45am to 11:45 am
• JDBC - Recap

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:-
28-07-2022 Driver, DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types 2
https://www.tutorialspoint.com/jdbc/jdbc-introduction.htm
What is JDBC?
• JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity
between the Java programming language and a wide range of databases.

• The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database
usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
• Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an
underlying database.
• Java can be used to write different types of executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
• All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored
data.
• JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 3
Connection, Steps to create JDBC Application,JDBC Driver Types
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 JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable
of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers
and the Java application −

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:-
28-07-2022 4
Driver, DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Pre-Requisite

• We need to have a good understanding of the following two subjects


• Core JAVA Programming
• SQL or MySQL Database

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 5
DriverManager, Connection, Steps to create JDBC Application, JDBC Driver Types
Common JDBC Components
The JDBC API provides the following interfaces and classes −
• DriverManager
• This class manages a list of database drivers.
• Matches connection requests from the java application with the proper database driver using communication sub
protocol.
• The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
• Driver
• This interface handles the communications with the database server. You will interact directly with Driver objects very
rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details
associated with working with Driver objects.
• Connection
• This interface with all methods for contacting a database. The connection object represents communication context, i.e.,
all communication with database is through connection object only.
• Statement
• You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept
parameters in addition to executing stored procedures.
• ResultSet
• These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an
iterator to allow you to move through its data.
• SQLException
• This class handles any errors that occur in a database application.
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:-
28-07-2022 6
Driver, DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
The JDBC 4.0 Packages

• The java.sql and javax.sql are the primary packages for JDBC 4.0.

• The new features in these packages include changes in the following areas −
• Automatic database driver loading.
• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 7
Connection, Steps to create JDBC Application,JDBC Driver Types
What is JDBC Driver?

• JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.
• Example:
• JDBC drivers enables to open database connections and allows to interact with it by sending SQL or database
commands then retrieving results and to store that in Java.

• The Java.sql package that ships with JDK, contains various classes with their behaviours defined.

• Third party vendors implements the java.sql.Driver interface in their database driver.

//jdbc driver
import java.sql.*;

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 8
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
DriverManager class
• The DriverManager class acts as an interface between user and drivers.
• It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver.
• The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver().
• Useful methods of DriverManager class
Method Description

1) public static void registerDriver(Driver driver): is used to register the given driver with DriverManager.

2) public static void deregisterDriver(Driver driver): is used to deregister the given driver (drop the driver from the list) with
DriverManager.

3) public static Connection getConnection(String url): is used to establish the connection with the specified url.

4) public static Connection getConnection(String url,String userName,String is used to establish the connection with the specified url, username and
password): password.

Example: to connect to mysql database using the JDBC Driver com.mysql.jdbc.Driver


Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cmrdatabase","root","");
//here cmrdatabase is database name, root is username and password is blank
Example: to connect to oracle database using the JDBC Driver oracle.jdbc.driver.OracleDriver
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 9
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Steps to create JDBC Application

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR


28-07-2022 University, Common JDBC Components:- Driver, DriverManager, 10
Connection, Steps to create JDBC Application,JDBC Driver Types
https://dotnettutorials.net/lesson/steps-to-design-jdbc-applications-in-java/
Steps to create JDBC Application
Steps 1: Establishing Connection : Loading and Registering • Step by Step Process that need to follow how to perform
CRUD (create, read, update and delete ) operations in
JDBC driver
Java.

Step 2: Creating or Requesting for database connection

Step 3: Creating Statement Object:

Step 4: Submitting the SQL Statement:

Step 5: Close the Connection

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 11
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Steps 1: Establishing Connection : Loading and Registering JDBC driver

• Establishing the database connection in a java program involves two steps


• Step1. Loading JDBC driver from secondary memory into primary memory.
• First, you need to load the driver or register it before using it in the program. Registration is to be done
once in your program.
• In java.lang.Class class, there is a static method “forName”.
• This method is used to load the JDBC driver into the application process space.

Syntax: public static void forName(String className) throws ClassNotFoundException

• You can register the Driver by following two ways :


1. Class.forName(“driver class name”) : Here we load the driver’s class file into memory at the runtime. No need
of using new or creation of objects.
2. DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we
call the constructor of the driver class at compile time.

• When the forName() method is successfully executed, three things happen in the background
1.The driver class is loaded into memory.
2.The driver class object is created.
3.The driver class is registered with DriverManager.
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 12
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Step2: Creating or Requesting for database connection

In order to establish a communication with the database, you must first open a JDBC connection to the database. After loading the driver,
establish a connection. In java.sql.DriverManager class there is a static method “getConnection”. This method is used by the java
program to request the database connection. Following are three methods of DriverManager.getConnection() :
1.getConnection(String url)
2.getConnection(String url, Properties prop)
3.getConnection(String url, String user, String password)
Syntax : public static Connection getConnection(String url,String name,String password) throws SQLException
Example: Connection con = DriverManager.getConnection(“connection string”, “user name”, “password”);

• Once the above statement is executed, the client connects to the


database server. Object-oriented representation of JDBC client’s
session with the database server is nothing
but java.sql.Connection object

Note:
• Internally getConnection() method call connect method of
connection class.

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager, Connection,
28-07-2022 13
Steps to create JDBC Application,JDBC Driver Types
Step 3: Creating Statement Object:

• The createStatement() method of the Connection interface is used to create a statement. The object of the statement
is responsible to execute queries with the database.

Syntax : public Statement createStatement()throws SQLException


Example: Statement st = con.createStatement();

The Statement object is designed to submit SQL statements from the JDBC client to the DBMS (via JDBC driver).

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 14
Connection, Steps to create JDBC Application,JDBC Driver Types
Step 4: Submitting the SQL Statement:

• The java.sql.Statement object has two important methods to submit SQL statements to the DBMS

1.executeUpdate(String dml):–
1.The executeUpdate(SQL query) method of Statement interface is used to execute queries of updating/inserting.
2.This method is used to submit DML (INSERT, UPDATE, and DELETE) SQL statements.

2.executeQuery (String drl):–


1.The executeQuery() method of the Statement interface is used to execute queries to the database.
2.This method returns the object of ResultSet that can be used to get all the records of a table.
3.This method is used to submit the SELECT statement.

Syntax : public ResultSet executeQuery(String sql) throws SQLException

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 15
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Step 5: Close the Connection

• By closing the connection object statement and ResultSet will be closed automatically.
• The close() method of the Connection interface is used to close the connection.

Syntax : public void close()throws SQLException

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 16
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Database Connectivity with Oracle

• To connect the java application with the oracle database, we need to know the following information for the oracle
database:
1. Driver class:
• The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL:
• The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe

where jdbc is the API oracle is the database, thin is the driver

jdbc:oracle:thin://localhost:1521/xe XE is the service name

localhost or IP address can be used, it


is server name on which mysql is 1521 is the port number
running,

Note: All these information can be obtained from the tnsnames.ora file.
3. Username: system is the default username for the oracle database.
4. Password: tiger is the default password or whatever user has given at the time of installing the oracle database.
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 17
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Sample Program to connect with Oracle database

Create a Table: Please execute the below SQL query to create a table:
CREATE TABLE emp (id number(8) primary key, name varchar2(25), age number(3));

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",“tiger");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp values(6,’Rahul',50)");


//int result=stmt.executeUpdate("update emp set name=‘Rahul Gandhi' where id=6");
int result=stmt.executeUpdate("delete from emp where id=33");
System.out.println(result+" records affected");
con.close();
}
}

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 18
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to follow following steps.
1. Driver class:
• The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL:
• The connection URL for the mysql database is given below

where jdbc is the API mysql is the database

cmrdatabase is the
jdbc:mysql://localhost:3306/cmrdatabase database name

localhost or IP address can be used, it


is server name on which mysql is 3306 is the port number
running,

3. Username:
• The default username for the mysql database is root.
4. Password:
• Default password is will be blank in mysql or the password given by the user at the time of installing the mysql database
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 19
Connection, Steps to create JDBC Application,JDBC Driver Types
Example: Program to connect mysql database and fetch records from employee table
MYSQL

create database cmrdatabase;


use cmrdatabase;
create table emp(id int(10),name varchar(40),age int(3
));

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cmrdatabase","root","");
//here cmrdatabase is database name, root is username and password is blank
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 20
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
• JDBC Driver Types.

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 21
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
JDBC Drivers Types

• JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in
which Java operates.

• Sun Microsystem has divided the implementation types into following four categories:

Type 1 − JDBC-ODBC Bridge Driver

Type 2 − JDBC-Native API

Type 3 − JDBC-Net pure Java

Type 4 − 100% Pure Java

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:-
28-07-2022 22
Driver, DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Type 1 − JDBC-ODBC Bridge Driver

• In this type of driver, A JDBC bridge is used to access ODBC drivers installed on each client machine.
• Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target
database.

The JDBC-ODBC Bridge that comes


with JDK 1.2 is a good example of this
kind of driver.

Note: When Java was first introduced, 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.
28-07-2022 Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, 23
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Type 2 − JDBC-Native API
• In this type of 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.

• If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete.

• Advantage:
• Speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver,
28-07-2022 24
DriverManager, Connection, Steps to create JDBC Application,JDBC Driver Types
Type 3 − JDBC-Net pure Java

• In this type of 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.

• Here application server works as a JDBC "proxy,"


meaning that it makes calls for the client
application.

• To use this driver type, we need to know 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


driver to communicate with the database.

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 25
Connection, Steps to create JDBC Application,JDBC Driver Types
Type 4 − 100% Pure Java

• In this type of driver, a pure Java-based driver communicates directly with the vendor's database through socket
connection.
• This is the highest performance driver available for the database and is usually provided by the vendor itself.

• This kind of driver is extremely flexible, you don't need 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

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 26
Connection, Steps to create JDBC Application,JDBC Driver Types
Which Driver should be Used?

• Type 1 driver is recommended for development and testing purposes, It is not considered a deployment-level driver

• Type 2 drivers is recommended, for situations, where a Type 3 or Type 4 driver is not available yet for your database.

• Type 3 driver is recommended, If your Java application is accessing multiple types of databases at the same time

• Type 4 driver is recommended, if we are accessing any one of the following type of database
• Oracle
• Sybase
• IBM

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR University, Common JDBC Components:- Driver, DriverManager,
28-07-2022 27
Connection, Steps to create JDBC Application,JDBC Driver Types
Following table lists down the popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format


MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName jdbc:mysql://localhost:3306/cmrdatabase

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port jdbc:oracle:thin://localhost:1521/xe


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR


28-07-2022 University, Common JDBC Components:- Driver, DriverManager, 28
Connection, Steps to create JDBC Application,JDBC Driver Types
MCQ

Prof. Mohan Reddy . Y, Assistant Professor, SOSS, CMR


28-07-2022 University, Common JDBC Components:- Driver, DriverManager, 29
Connection, Steps to create JDBC Application,JDBC Driver Types

You might also like