Adv Java Notes
Adv Java Notes
-------------------------------------
> 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.
Ex:-
Apache POI, Jaxcel, Jdbc-api, Servlet-api etc.
***)
There are two different forms of API:->
a) I form of API b) II form of API
b) II form of API:->
--------------
Eg:- JDBC Api, Servlet Api etc
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.
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)
> 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
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:-
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:-
// import java.sql.*;
static
{
DriverManager.registerDriver( d ) ;
}
// Jdbc till now whatever completed + Exception --- tomorrow
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):-
----------------
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");
> In this step, We have to establish the connection between java application and the DB Server
by using " getConnection() " Method.
> 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") ;
> 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()
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.
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) ****
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:-
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:-
---------------------
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 " ? ".
b) The number of data must exactly match with the number of Placeholder.
Ex:-
sid=sc.nextInt();
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..
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();
> JDBC Transaction is considered to be a Single Bussiness Unit which may have multiple SQL
Statements which must be executed.
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
> 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.
==================================================