You are on page 1of 14

API(Application Programming Interface):-

-------------------------------------
> It is used for inter-application communication.
> API is used for " inter-application communication " i.e one application can communicate with
another application with the help of API to achieve loose coupling.

***> The backbone of API is Abstraction

Ex:-
Apache POI, Jaxcel, Jdbc-api, Servlet-api etc.

--> Contents of API's:-


> The contents of API are interfaces, helper class and Implementation class given in the form
of " .jar " file.

***)
There are two different forms of API:->
a) I form of API b) II form of API

a) I form of API :->


--------------
> This form of API contains interfaces, Helper class, implementation class in the form of jar file.
> This form of API is exposed to developers only to write logic or code.
Eg:-
Apache POI, Jaxcel etc.

b) II form of API:->
--------------
Eg:- JDBC Api, Servlet Api etc

**) JDBC API:-


-----------
> JDBC API contains interfaces and Helper Classes in the form of jar file.
--> If i want to develop any JDBC Application, we need JDBC API because it provides several
interfaces and Helper Class which is used for database Communication.
--> Implementation classes is provided by the respective DataBase Vendors(Owner).
> JDBC API is distributed in 2 different packages
a) java.sql b)javax.sql

b)javax.sql---> It is an extension of java.sql, it contains several or some additional interfaces


than java.sql.

> Few of the interfaces of JDBC API are:-


-------------------------------------
a) Driver
b) Connection
c) Statement
d) PreparedStatement
e) CallableStatement
f) ResultSet
etc......

> JDBC API contains only one HelperClass in it...


DriverManager

JDBC Driver:-
----------
> JDBC Driver is an implementation of JDBC API.
> JDBC Driver contains implementation classes .
> JDBC Driver is always specific to particular DB Server/Vendor.
> JDBC Driver are provided by the respective DB Server/Vendor.

Advantage of JDBC:-
-----------------
> We can achieve loose coupling between java application and db server.

Port Number:-> port no is the one which helps us to get connected with particular server.

Oracle ---> 1521


my-sql ---> 3306
ms-sql ---> 1433
Derby ---> 1527

Host:-> It is a platform on which all the application can be executed.

> There are two different types of host-present namely:-


a)Local Host b)Remote(Global) Host

a) Local Host:- In case of local host, the application are limited to only a particular system.
Ex:-StandAlone Application(ex:---Desktop Application)

b) Remote Host:- In case of Remote host, the application are not restricted or limited to any
system.
Ex:- Any Real time Application ( Youtube etc)

URL(Uniform Resource Locator):-


> It is the path or address using which, we can access the resources uniquely over the network.

Constraints of Url are:->


----------------------
Protocol, Host+PortNo, ResourceName

> In case of URL, Data refers to key and Value pair provided by the user. ( Servlet )
> The protocol for the Web Applications:- http(Hypertext Transfer Protocol) / https(Hypertext
Transfer Protocol Secure)
> The protocol of JDBC is jdbc:sub-protocol(Respective DB Server)

Syntax:-
------
mainprotocol:sub-protocol://Host:PortNo/DB_NAME(Optional)

My-Sql(DB SERVER):-
-----------------

Local Host:-
-----------
Host Information User Information

jdbc:mysql://localhost:3306?user=root&password=root

Remote Host:-
-----------

jdbc:mysql://192.168.10.16:3306?user=root&password=root

Oracle(DB SERVER):-
----------------

Local Host:-
----------

jdbc:oracle://localhost:1521?user=scott&password=tiger

Remote Host:-
----------

jdbc:oracle://192.168.10.16:1521?user=scott&password=tiger

***] Implementation Classes == Driver Classes !!!!!


-----------------------------------------------------

FQCN(Fully Qualified Class Name)


-------------------------------
Package Name.Class Name

Standard Way of creating a package structure:-


--------------------------------------------
> com/org.company_name.Application_name.

Different Driver Class provided by Respective db server or vendor:-


-----------------------------------------------------------------

DB server FQCN
--------- --------------------------------------------
Mysql :- com.mysql.jdbc.Driver

Oracle :- oracle.jdbc.driver.OracleDriver

Ms-sql :- com.microsoft.sqlserver.jdbc.SqlServerDriver

Derby :- org.apache.derby.jdbc.EmbeddedDriver

a) All the Driver classes which is a part of JDBC Driver are provided by the respective DB servers
or vendors in the form of jar file.

b) All the Driver classes must mandatory implements java.sql.interfaces which is a part of jdbc
API.

***}
Why is JDBC Driver is an implementation of JDBC API ?

---> Since all the Driver Classes must mandatorly implements java.sql.Interfaces which is a part
of JDBC API, Hence JDBC Driver is an implementation of JDBC API.

**Definition of JDBC:-
------------------
Java DataBase Connectivity [JDBC] is specification given in the form of abstraction API to
achieve loose coupling between Java Application and DB Server.

[Job]***)

Steps of JDBC:-
-------------
> There are 6 different steps present in jdbc:-

a) Load and register the Driver[Driver refers as Driver Class].


b) Establish the connection with a DB server.

c) Create a platform or Statement.

d) Execute the Sql query or SQL statements.

e) Process the Resultant Data[Optional].

f) Close all the connection( Costly Resources ).

Specification of JDBC:-
---------------------
There are 3 different specificatons present for jdbc namely:-

a) All the Driver Class must contain one Static Block in it.

b) All the Driver Class must mandatory implements java.sql.interfaces which is a part of jdbc
api.

c) All the Driver Class must mandatorily be registered with DriverManager by using static
method called registerDriver() Method.

Ex:-

Mysql (Data Base) :-


-----------------
" + " --- > public , " - " ---> private , " # " ---> protected

// import java.sql.*;

+ class Driver implements java.sql.interfaces

static
{

Driver d = new Driver();

DriverManager.registerDriver( d ) ;

}
// Jdbc till now whatever completed + Exception --- tomorrow

1) Load and register the Driver[ Driver refers Driver classes ] :-


-----------------------------------------------------------
> In this steps, we have to load and register the Driver classes which is a part of JDBC Driver and
which are provided by the database vendors.
> The Driver classes loaded and registered in 2 different ways namely:-
a)Manually
b)by using forName()

a)Manually:-
> creating an object of Driver class and registered it with DriverManager by using static method
called registeDriver() Method.

My-sql(DB Server):-
----------------
Driver d=new Driver();

DriverManager.registerDriver(d);

Oracle(DB Server):-
----------------

OracleDriver od=new OracleDriver();

DriverManager.registerDriver( od );

b)2nd way:-
--------
> By using static method called forName() Method, we can load and register the Driver classes
which is a part of JDBC Driver.

Syntax:-
-------
lang package:- java.lang.*;

Mysql:-
------

Class.forName("com.mysql.jdbc.Driver");
-------------------------------------- <---[ checked Exception(ClassNotFoundException) ]

Oracle:-
------

Class.forName("oracle.jdbc.driver.OracleDriver");

> It will load and register the Respective Driver Classes..

2) Establish the connection with a DB Server:-


-----------------------------------------

> In this step, We have to establish the connection between java application and the DB Server
by using " getConnection() " Method.

> Factory/ Helper Method:- It is used to create implementation object.

> getConnection():- It is Factory/ Helper Method which is used to create and return the
implementation object of " Connection " interface based on URL, Hence the
Return type will be Connection interface, And it is static in nature.

> There are 3 different overloaded variants(forms) of getConnection() Method which are as
follows:-

a) getConnection(" URL") ;

b) getConnection(" URL " , Properties info) ;

c) getConnection(" URL " , " User ", " Password ") ;

> getConnection()- present in a HelperClass called " DriverManager ".

> Whenever we use getConnection() Method, it throws a checked Exception called SQL
Exception.

java.sql.Connection:- It is an interface which is a part of jdbc API and the implementation are
provided by the respective DB vendors as a part of JDBC Driver.

java.sql.DriverManager:- It is a Helper class which is a part of JDBC API and which contains 2
important static methods in it namely:-

a)registerDriver() b)getConnection()

3) Create a Platform or Statement:-


------------------------------
> we need to create a Platform or Statement in order to execute the SQL Queries or SQL
Statements.
> A Statement or Platform can be created either by using " Statement interface " or "
PreparedStatement interface " or " CallableStatement interface ".

java.sql.Statement:- It is an interface which is a part of JDBC API and the implementations are
provided by respective DB Vendors or Servers as a part of JDBC Driver.

Statement :-
---------
> if i want to create the platform by using " Statement " interface, have to use "
createStatement() " Method.
> " createStatement() " present in a Connection interface, It is a factory or helper method
which is used to create and return the implementation object of " Statement "
interface, Hence the return type for createStatement() is Statement interface.

4) Execute the SQL Query or SQL Statements:-


---------------------------------------
> In order to execute the Sql queries or Sql statements, we have 3 different methods present
namely:-

a) execute() b) executeUpdate() c) executeQuery() [ DQL{ SELECT } , DML{


INSERT, UPDATE , DELETE} etc]

> All these methods are present in Statement interface. !!!!!

a) execute():-
--------
> execute Method is a Generic Method, Since it is is used for any type of Sql Queries.
> Hence, the return type is boolean.
> By default, execute() returns a boolean True in case of DQL and boolean False in case of DML.

b) executeUpdate():-
--------------
> executeUpdate() is a Specialized Method since, it is used to execute Only DML Queries or
DML Statement.
> The outcome of DML is 0-n integer value which gives the total no. of records affected in the
DB server.
> Hence the return type is interger.
> whenever we try to execute DQL using this method, it throws SQL Exception .

5) ****

6) Close the connection:-


-------------------
> We close the connection in a finally block, by using if condition to avoid null pointer
Exception.
> All the interfaces in jdbc Api, we have to close it...!!!!

> Each Query is making one db call.


> The more no of db calls, will decrease the performance of an application.
> Each db call is considered as costly resouces.

Fetching the data from Database Server:-


---------------------------------------
> Whenever we execute DQL Query, we get a result which is referred as Resulatant or
Processed Data.
> The Processed or Resultant Data can be fetched by ResultSet Interface which is a part of JDBC
API.

java.sql.ResultSet

> It is an interface which is a part of JDBC Api and the implementations are provided by
respective Database Server or vendors as a part of JDBC Driver.
> A set of methods of ResultSet interface are used to fetch the Processes or Resultant data
which are known as getXXX().
> There are two different methods which are overloaded methods present in a ResultSet
Interface:-

a) +XXX getXXX(int coloumnnumber/coloumnindex ) // ( coloumn number ---- coloumn index )

b) +XXX getXXX(String coloumnname/coloumnlabel ) // ( coloumn name ----- coloumn label )

--> If datatype is integer:-

a) +int getInt(int coloumnnumber)

b) +int getInt(String coloumnname)

--> If datatype is String:-

a) +String getString(int coloumnnumber)

b) +String getString(String coloumnname)

--> If datatype is Double:-

a) +double getDouble(int coloumnnumber)

b) +double getDouble(String coloumnname)


# The return type of getXXX() method is respective data-type.
# The return type of setXXX() method is void.

// hasNext() --- next() // Collection

// next() --- getXXX() // JDBC

next():-

> It is used to check whether the next record is present or not and returns a boolean value
called true or false but not the record.

+ boolean next()

executeQuery():-
------------
> It is a specialzed method which is used to execute only DQL Queries.
> The outcome of a DQL is Processed or Resultant Data which can be fatched by ResultSet
Interface which is a part of JDBC Api.
> Hence, the Return type for executeQuery() is ResultSet interface.
> whenever we try to execute DML query using this method it throws an exception called
SQLException.
Syntax:-
-------
+ResultSet executeQuery("Only DQL")

Implementation Object:-
---------------------

ResultSet rs = stmt.executeQuery(" DQL ");

// insert into thane.student values(1,'Oats',45.3); // Hard-coding


// Oats -- Wheat

PlaceHolder:-
----------
> It is a parameter which holds Dynamic values at the run time by the User.
> In case of JDBC, place holder is represented by as " ? ".

Declaration of PlaceHolder in the Query:-


---------------------------------------

String inQry=" insert into thane.student values(?,?,?) ; // 1 - id 2 - name 3 - perc


String inQry1=" insert into thane.student values(?,?,?) ;

String upQry=" update thane.student set Product_Name = ? where id = ? ; //2 placeholders -- 2


times

String delQry=" delete from thane.student where id = ? ;

String selQry=" select * from thane.student where id = ? ;

Rules to set the data for a PlaceHolder:-


---------------------------------------
There are 3 different rules to set the data for PlaceHolder namely:-

a) We have to set the data for a Placeholder before the execution.

b) The number of data must exactly match with the number of Placeholder.

c) We have to set the data for a Placeholder by using setXXX().

+void setXXX(int placeholdernumber/placeholderindex, XXX data)

Ex:-
sid=sc.nextInt();

setInt(1, 15); // setInt(1, sid);

setString(2, "Steve"); // setString(2, sc.next());

setDouble(3, 34.5); // setDouble(3, sc.nextDouble());

java.sql.PreparedStatment:-

> It is an interface which is a part of jdbc api, and its implementation are provided by respective
db server or vendors as a part of JDBC Driver.
> PreparedStatment interface is sub-interface of Statement interface.
> It supports the concept of PlaceHolder.
> It supprts the concept of Execution Plan( Compile once execute many times ).
> In case of PreparedStatement, the query is passed at the time of implementation object
creation of PreparedStatement interface.
Hence, PreparedStatement are also known as Pre-compiled Statement.

Syntax:-
java.sql.PreparedStatement pstmt = con.prepareStatement("Query");

> prepareStatement() is a factory or helper method which creates and return the
implementation object of PreparedStatement interface.
> Hence, the return type for prepareStatement() is PreparedStatement interface.

Note[JOB]:-
** since Compilation takes place each time along with Execution whenever we execute query
using Statement Interface, Performance of an application decreases.
Hence, it is a good paractice to make use of PreparedStatement interface to deal with
multiple records.

#####

Statement interface:-
-------------------
Statement stmt = con.createStatement();
stmt.executeUpdate("Qry"); // Complication and Execution
stmt.executeUpdate("Qry");

PreparedStatement interface:-
---------------------------
PreparedStatement pstmt=con.prepareStatement("Qry"); // pass the qry while creating a
platform
pstmt.executeUpdate();
pstmt.execcuteUpdate();

Batch Update:-
-------------
Batch:- it is a collection of only DML Query.

Need of Batch:- Batch Update is needed to make one single data base call and affect multiple
records of multiple tables at once..

Advantage:- Batch Update greatly improves the performance of an application.

> Batch Update is applicable only for DML Queries.


> In case of Batch Update after adding all the DML Queries into the Batch, the entire Batch will
execute only once.
> There are 2 methods w.r.t Batch.
a) addBatch() b) executeBatch()

a) addBatch():- This is used to add all the DML Queries into the Batch.

b) executeBatch():-
> This method is used to execute all the DML Queries present inside the Batch only once by
making one single DB call.
> It returns an interger Array.
> The size of the integer Array represents the total no of DML Queries added into the Batch.

Note***:-
> Whenever we use Batch with Statement interface, then one single batch can contain all types
of DML Queries in it.
> Whenever we use Batch with PreparedStatement interface, then one single batch can contain
only one DML Query in it.
Hence, Batch with Statement interface is faster in Performance.

JDBC Transaction
================
> Exchange data or information between two media is known as Transaction.
> By default, the AutoCommit mode is set to boolean true value because of which all the data
are automatically saved into the Database Server whenever we perform any Database
operation.
> We can explicitly disable AutoCommit mode by using setAutoCommit() and passing a boolean
false argument.

Syntex:-
+void setAutoCommit()
eg:-
con.setAutoCommit(false);
Note:-
* We have to disable the AutoCommit mode before we begin the transaction but after
establishing a connection with Database Server.

> Once the AutoCommit mode is disabled we have to explicitly save the data into the Database
Server by using commit() at the end of transaction.

Syntex:-
+void commit()
eg:-
`con.commit();

> If anyone of the database operation fails, then the rollBack() operation is called which is used
to rollBack Entire executed Database Operation and transaction starts from begning.

Syntex:-
+void rollBack()

eg:-
con.rollBack();

Definition for JDBC Transaction:

> JDBC Transaction is considered to be a Single Bussiness Unit which may have multiple SQL
Statements which must be executed.

Need for JDBC Transaction:-


-------------------------
> JDBC Transaction is needed to maintain Data Consistency in the Database Server.

Advantage of JDBC:-
-----------------
> It is used to achieve ACID Properties or rules where A refers to Atomicity, C refers to
Consistency, I refers Isolation, D for Durability

Atomicity: Atomicity means Do Everything or Do Nothing.

> Do Everything refers to Complete or Successful transaction where if all the Database
operation are succesfully executed, then the data's are saved into the Database Server leading
to Data Consistency.
> Do Nothing refers to Unsuccessful or Uncomplete transaction where if any of the Database
operation fails, then the rollBack opertion is called which is used to rollback the Entire
execeuted Database operation and transaction starts from begining without saving any data
into the Database Server due to data inconsistency.

SavePoint:-
=========
Syntex:-
java.sql.Savepoint sp=con.setSavePoint();

setSavePoint():-
--------------
> setSavePoint() is a factory or helper method which is used to create and return
implementation object of Savepoint interface.
> Hence the return type of setSavepoint() is Savepoint interface.

==================================================

DDL - Data Definition Language

create -- create table table name (coloumn_name(data_types), )

You might also like