You are on page 1of 10

JDBC

=>JDBC:- Java DataBase Connectivity is a specification given in the form of Abstraction API
to achieve loose coupling between java application & database server.
* The backbone of API is Abstraction.
* The o/p of abstraction is loose coupling which can be achieved with the help of interface.
=>Loose Coupling:- Change in the implementation which doesnot effect the user is known as
loose coupling.
=>Interface:- It is a media to communicate between user & any device.
=>Abstraction:- Hidding the implementations & providing the functionalities to the user with the
help of interface is known as abstraction.
=>Q. Why are the implementations hidden in case of abstraction?
Ans. To reduce the complexity or to make the implementations look simple and neat for the user.
=>Q.(M.I.) Why is a class made abstract when it contains only concrete methods in it?
Ans. So that further enhancements or modifications made doesnot effect the user.
Ex. Any new upgradations made to an existing applications or installations of new
application.
Ex. Loose Coupling=>Change in application(which doesnot effect the user).
Tight Coupling=>Change in ATM PIN(which effects the user).
=>Steps of JDBC
There are 6 different steps present in jdbc namely.
1. Load & Register the Driver
Load & Register the Driver=>Driver Class=>Respective DBS/Vendors=>JAR
* Respective DBS/Vendors
Respective DBS/Vendors Driver Class Port Number
=> Oracle => OracleDriver => 1521
=> MySQL => Driver => 3306
=> (Microsoft)MSsql => SqlServerDriver => 1433
=> Derby => EmbeddedDriver => 1527
Load & Register the Driver

Manually Static Method

Creating object of Driver Class & forName()=>package=>java.lang


Registering with Driver Manager
by using static method registerMethod(). Checked exception=>ClassNotFoundException
declared=>Class
returns=>Respective class based on FQCN
(Fully Qualified Class Name).
=>(M.I)(V.V.V.Imp)Specifications of JDBC
* There are 3 different specifications present in JDBC namely.
1. All the Driver classes must contain one static block in it.
2. All the Driver classes must mandatorly implements java.sql.Driver interface which is a part of
JDBC API.
3. All the Driver classes must mandatorly be registered with Driver Manager by using a static
method called registerDriver().
=>Q. Why is JDBC Driver an implementation of JDBC API?
Ans. Since all the Driver classes must mandatorly implements Driver interface of JDBC API.
Hence, JDBC Driver is an implementation of JDBC API.
2. Establish a connection with DB Server
* Establish a connection with DB Server=>Connection between Java Application & DB Server.
* Connection between Java Application & DB Server=>By using getConnection()--static method.
* getConnection() returns=>Implementation Object of Connection Interface based on URL.
* Polymorphism exhibited(MySQL/Oracle/Derby) in JDBC=>getConnection()
* getConnection() has 3 Overloaded variants
1. getConnection(String URL)
2. getConnection(String URL,Properties info.)
3. getConnection(String URL,String User,String password)
=>Polymorphism exihibited in JDBC by using getConnection() where getConnection() returns
implementation object of Connection Interface based on the URL’s of respective DB’s/Vendors.
3. Create a statement or platform
Why=>To execute SQL Queries or SQL Statements
Ways=>3 Ways=>Statement=>Prepared Statement=>Callable Statement=>Interfaces of JDBC API
| (Pre-Compiled) (Pre-Compiled)
| | |
Impln Object Impln Object Impln Object
| | |
Factory/Helper Method Factory/Helper Method Factory/Helper Method
| | |
createStatement() prepareStatement(Qry) prepareCall(Qry)(V.Imp.)

4. Execute the SQL Queries or SQL Statements


* 3 methods=> execute() => executeUpdate() => executeQuery()
=> execute() => Declared=>Statement
|
Generic Method
|
Used to execute any SQL Queries/Statements.
|
Return type=>Boolean =>TRUE=>DQL
=>FALSE=>DML/DDL
=> executeUpdate() => Declared=>Statement
|
Specialised Method
|
Used to execute only DML Queries
=>Outcome=>0-n integer value which gives total no of records affected in DBS.
|
Return type=>int
=> executeQuery() => Declared=>Statement
|
Specialised Method
|
Used to execute only DQL Queries
=>Outcome=>Processed/Resultant Data stored in Cursor/Buffer Memory=>Fetched=>JDBC API
|
Return type=>ResultSet Interface => JDBC API

5. Process the Resultant Data(optional)


Why=>Since it is associated only with the DQL query & is stored in Cursor/Buffer Memory.
6. Close All the Costly resources
* Resources which uses system properties are known as costly resources.
* Costly resources must be closed to increase the performance of an application.
* All costly resources must be closed within the Finally block by using if condition to avoid
NullPointerException.
=> Placeholder
* It is a parameter which holds dynamic values at the runtime by the user.
=> Rules to set the data for a placeholder
* There are 3 different rules to be followed in order to set the data for a placeholder namely.
1. We have to set the data for a placeholder before the execution.
2. The no. of datas must exactly match the no of placeholders.
3. We have to set the datas for a placeholder by using setXXX() methods.
* In order to fetch the processed or resultant data from the cursor/buffer memory we have to
make use of getXXX() methods.
* There are two different overloaded variants of getXXX() methods present namely.
=>getxxx(int ColumnIndex/ColumnNumber)=>ResultSet=>JDBC API
=>getxxx(String ColumnLabel/ColumnName)=>ResultSet=>JDBC API
=>(M.I./V.V.Imp) By Default the return type for getXXX() methods are respective datatypes
whereas the return type of setXXX() methods is void.
=>Outcome of DQL=>Processed or Resultant Data stored in Cursor/Buffer Memory and can be
fetched by using => ResultSet => 3 methods => getXXX(),next(),absolute()
|
Interface=>JDBC API
|
Impln Object
|
Factory/Helper Method
|
getResultSet()
=>getXXX()=>Fetched Processed or Resultant Data from Cursor/Buffer Memory
=>next()=>Why=>Checks next record present in Cursor/Buffer memory &
returns Boolean True/False but not record.
=>When=>Minimum records present in Cursor/Buffer memory.
=>absolute()=>Why=>Checks particular record present in Cursor/Buffer memory based on
parameter called int RowNumber & returns Boolean True/False but not record.
=>When=>n records present in Cursor/Buffer memory.
=>(M.I.,V.V.V.Imp) Whenever the no. of datas exceeds the no. of placeholders, the output is
SQLException thrown by respective DBS/Vendors.
Query= ? ? ?
Id Name Perc
1 Mayank 64.32 Male => SQLException
Query=? ? ?
Id Name Perc
setInt(1,1);
setString(2,”Jaya”);
setDouble(3, 64.76);
setString(2,”Shwetha”);
O/P:- 1 Shwetha 64.76=>Overridden value will be inserted
=>Q.(M.I.,V. V.V.Imp.) What is the role of placeholder in case of Prepared Statement &
Callable Statement Interface?
Ans. 1. In case of Prepared Statement Interface placeholder is used to take dynamic values at the
runtime by the user.
2. In case of Callable Statement Interface placeholder is used to take the value for
IN & OUT parameters.
OUT
*IN & OUT Select Username from Btm.User
where Name= ? and Password=?;
IN IN
=>BatchUpdate
# Definition of Batch
* Batch is a collection of only DML Queries.
# Need for Batch
* To make 1 single DB call & affect multiple records of multiple tables at once.
* Real time Ex.--Creating Groups to share Data.
# Advantage of Batch
* Reduces DB calls which helps in increasing the performance of an Application.
* There are two methods associated with batch namely.
=>addBatch()=>Adds all the DML queries into Batch.
=>executeBatch()=>Execute all DML queries in the batch only once by making one single DB call.
* (M.I.,V.V.V.Imp.) executeBatch() returns integer array[]
* Size of integer array represents total number of DML queries added into batch.
* Sequence of the integer array represents the same sequence in which DML queries are added into
the batch.
=>Q.(M.I.,V.V.V.Imp.) In general, is Statement Interface is faster in performance or Prepared
Statement Interface?
Ans. In general Prepared Statement is faster than for 2 reasons
1. It supports placeholders to take dynamic values at the runtime by the user.
2. It supports execution plan that means compile once & execute many times.
=>Q.(M.I.,V.V.Imp.) Is Batch with respect to Statement Interface advantageous or Prepared
Statement ?
Ans. Batch Statement Batch Prepared Statement
DML DML
Insert qry Insert qry
+ Batch Prepared Statement
Update qry DML
+ Update qry
Delete qry Batch Prepared Statement
DML
Delete qry
=> 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 respect to Prepared Statement Interface, then one single batch can
contain only one DML query in it. Hence Batch with respect to Statement Interface is advantageous.

=> JDBC Transactions


# Transactions
* Exchange of data or information between two medias is known as Transaction.
# Need for Transaction
* To maintain data consistency in the DB Server(only valid datas)
# (V.V.V.Imp.) Advantage of JDBC Transaction
* JDBC transaction is used to achieve ACID properties or ACID rules where A for Atomicity,
C for Consistency, I for Isolation, D for Durability.
=>Q. Relate JDBC transaction with Atomicity & Explain?
Ans. Atomicity means Do Everything Or Do Nothing.
=> Do everything refers to complete or successful transaction where if all the DB operations are
successfully executed, then the Datas are considered to be valid which is saved into DB server
leading to Data consistency.
=> Do nothing refers to incomplete or unsuccessful transaction where if any one of the DB
operation fails then Roll Back operation is called which is used to RollBack entire executed DB
operations & transaction starts from begining without saving any datas into DB server due to data
inconsistency.
=>Q. (V.V.Imp.) How are all Datas automatically saved into DB server ?
Ans. By Default, Autocommit mode set to Boolean True because of which datas are saved
automatically into DB server.
=> Explicitly disable Autocommit
How=> By using setAutoCommit()
When=> Before beginning transaction but after establishing a connection with DB server.
=> To explicitly save datas we use commit() at the end of the transaction.
=> Successful Transaction
* If transaction details entered on an ATM machine is correct.
=> Unsuccessful Transaction
* If any one of the transaction details is not correct or not valid then unsuccessful/ incomplete
transaction.
=> Transactin with savepoint
* Re-entering the amount in place of existing amount.
=>By Default, the username for mySQL DB server is root.
SERVLETS
=> Server:- Server is a Software which manages all the resources along with which process the
client request & serve the client request.
=> The different servers are
1. DB Server => Used to deal with Database
Ex.- Oracle, MySQL, etc
2. Application Server => Used to execute a dynamic or real-time application.
Ex.- JBoss, IBMWebSphere & Oracle WebLogic.
3. Web Server => Used to execute web application
Ex.- Apache Tomcat & Oracle Glassfish
=> Deployment
* Making all the resources available to server is known as deployment.
* There are two types of deployment.
1. Manual Deployment =>All resources are made available to the server manually.
2. Automated Deployment =>All resources are made available to the server automatically with the
help of automated tools like Ant, Maven, etc.
* Jar means Java Archieve(compress).
* WAR means Web Archieve(compress) that means a compressed version of web application.
=> Important Points
* Web-apps=> Used to deploy all the web application on to Apache Tomcat Server.
* Work => Used to store the data w.r.t. translated servlet(conversion of JSP into a servlet)
* By default, the port no. for Apache Tomcat server is 8080
* Server basically performs two important tasks namely
1. Manages all the resources
2. Provides a runtime environment
* (M.I.) By default, the root tag for an xml file is <web-app>
* By default, the root tag for <load-on-startup> tag is <servlet> tag since <load-on-startup> tag
is a sub-tag of <servlet> tag.
* By default or the default welcome file or landing page is index.
* (V.V.Imp.) We can explicitly make a file as welcome file by renaming it as index.
* The current version of xml used is 1.0
=> Q. (V.V.Imp.) How are all the configurations made in web.xml understood by JEE
container?
Ans. All the custom tags or user defined tags are converted into 8-bit Unicode format.
* (M.M.Imp.) JEE container is responsible for loading all the applications sequencially one after
the other whenever the server is started.
* The total no of applications present in a server is n.
* Total no. of servlets present in an application name & servlet name must be unique.
=> (M.M.Imp.) Types of Http Request
* There are 8 different types of Http Request present namely.
1. POST 5. TRACE
2. GET 6. OPTION
3. PUT 7. HEAD
4. DELETE 8. CONNECT
=> (V.V.I.,M.M.Imp.) Whenever the type of request is not mentioned or configured, then by default
the type of request is GET request.
=>Q. (M.M.Imp.) How to carry the datas in a secured manner to the server?
Ans. By using POST request, In case of POST request, the datas are carried to the server as a part
of HTTP request body which is not displayed to enducer. Hence, the datas are secured.
=> (M.M.Imp.) Status message & status code
* The status message for the status code called 404 is client error.
* The status message for the status code called 500 is server error.
* The status message for the status code called 200 is success message.
=> Q. (M.M.I.,V.V.V.Imp.) Can we override service() method in Http servlet?
Ans. By default, servlet is multi threaded but it can be made Single Threaded in two ways.
1. By writing a servlet class which implements SingleThreadedModel(Marker Interface).
2. By making service() method as synchronized.
=> Q. (V.V.Imp,M.M.I.) How many lifecycle methods are present for a servlet?
Ans. There are three lifecycle methods present for a servlet namely.
1. init(ServletConfig)
2. service(ServletRequest req,ServletResponse resp)
3. destroy()
1. init(ServletConfig):- Used to initialize the resources of servlet object by taking ServletConfig as
a parameter.
* init() is called by the JEE container only once.
2. service(ServletRequest req,ServletResponse resp):- Used to process every client request.
* service() is called by the JEE container for multiple times or n no. of times.
3. destroy():- Used to close all the costly resources.
* destroy() is called by the JEE container only once but in two situations.
# Situation 1:- Whenever an application is closed, destroy() is called to close all costly resources
w.r.t. that application.
# Situation 2:- Whenever an application is redeployed on to server, destroy() is called to close
previously used costly resources.
=> (M.M.Imp.) Whenever any changes are made to an application, redeployment of an
application takes place.
=> Servlet Lifecycle begins whenever a servlet object is created.
=> Servlet chaining begins whenever a client makes any request to a servlet.
=> Session begins whenever a client makes any request to an application.
=> The scope of config object is limited to that particular servlet object since the datas present in
config object called init or initialization parameters is made available only to that particular
servlet object.
=> The scope of context object is throughout the application since the datas present in context
object called context parameters and attributes is made available throughout the application.
=> Q. Why the url remains the same in case of forward() & include()?
Ans. forward() and include() are methods of Request Dispatcher interface which works at the
server side.
* In case of forward(), the name of the chained resource or the url pattern of the chained
resource is not displayed to the enducer, Hence the url remains same.
* In case of include(), since the main or source servlets takes a request as well as gets back the
response, Hence the url remains same.
=> Q. (M.M.I.) Why sendRedirect() works at client side?
Ans. In case of sendRedirect() method, since the change in the url pattern takes place on the
browser. Hence sendRedirect() works at the client side.
* Whenever we use req.getRequestDespatcher(), then chaining takes place from one servlet to
another resources(HTML, JSP, Servlet) of the same application.
* Ex - Transfer of funds from one account holder to another account holder within the same
bank(of the same application).
* Whenever we use context.getRequestDispatcher(), then chaining takes place from one servlet to
another resources(HTML, JSP, Servlet) of different application.
* Ex – Transfer of funds/money from one account holder of one bank to another account holder of
different bank(of different application).
=> Servlet
* Definition:- Servlet is a server side java program which can perform all the three different types
of logic such as Presentation Logic, Persistance Logic & Business Logic along with which
process the Http Client Request & get back some Http Response.
* There two different types of servlet present namely.
1. Generic Servlet
2. Http Servlet
=> Generic Servlet HTTP Servlet
1. Not specific to any protocol. 1. Specific to HTTP protocol.
2. Doesnot support session. 2. It supports session.
3. It is an Abstract class present in javax.servlet. 3. It is an Abstract class present in
javax.servlet.http.
4. Contains 3 methods where one is abstract() & 4. Contains only concrete() without any
two are concrete(). abstract().
5. Abstract() is named as service() which has to be 5. Override respective concrete() called
overridden for 2 reasons. doXXX() for particular type of Http
(a.) service() is abstract() request.
(b.) service() takes a parameter called
ServletRequest & ServletResponse responsible
for processing client request.
6. Overriding init() & destroy() is optional since 6. Types of Http request are 8 namely
there are concrete(). POST TRACE
GET OPTION
PUT HEAD
DELETE CONNECT
=> Whenever we override service() or doXXX(), it throws an exception called ServletException,
IOException.
=> Servlet Config Servlet Context
1. It is an interface present in javax.servlet 1. It is an interface present in javax.servlet
package. package.
2. To create an implementation object, JEE 2. To create an implementation object, JEE
container calls factory/ helper method called container calls factory/helper method called
getServletConfig() after the servlet object getServletContext() at the time of
creation. application loading.
3.(V.V.I.) One implementation object is created for 3. One implementation object is created for
that particular servlet object. one entire application.
4. Datas present are init or initialization 4. Datas present are context parameters and
parameters. attributes.
5. These datas are made available only to that 5. These datas are made available throughout
particular servlet object. the application.
6. Scope of Config object is limited to that 6. Scope of Context object is throughout the
particular servlet object due to POINT 5. application due to POINT 5.
7. Init parameters can be declared in two ways 7. Context parameters can be declared only in
(a.) Web.xml:-Inside servlet tag due to POINT 6. web.xml but outside the <servlet> tag due
(b.) Annotation to POINT 6.
8. Init parameters can be fetched by using 8. Context parameters can be fetched by
getInitParameter(). using getInitParameter().
* config.getInitParameter(key) * context.getInitParameter(key)

=> Whenever n number of initParameter or n no of context parameters are declared then we use
getInitParameterNames().
=> (V.V.V.Imp.) Request(req) => Datas present in request object are UI/Form data.
|
Fetched => getParameter() => req.getParameter(key);
Scope of request object is throughout the application.
=> (V.V.V.Imp.) config => Datas present in config object are init/initialisation parameters.
|
Fetched => getInitParameter() => config.getInitParameter(key);
Scope of config object is limited to that particular servlet object.
=> (V.V.V.Imp.) context => Datas present in context object are context parameters & attributes.
|
Fetched => getInitParameter() => context.getInitParameter(key);
Scope of context object is throughout the application.
=> Parameter:- Data in the form of key & value pair where key must be unique string and value
can also be a string.
=> Attribute:- Data in the form of key & value pair where key must be a unique string and value
can be any object.
=> (V.V.Imp.) To add any object into scope, we use setAttribute().
+ void setAttribute(String key,Object obj);
=> To fetch any object back from the scope, we use getAttribute();
+ Object getAttribute(String key);
=> Q. (M.M.Imp.) What is JSP?
Ans. JSP is known as High Level Abstraction of Servlet that means the translation or conversion of
a JSP into a Servlet by the JEE container for first client request.
=> Q. (M.M.Imp.) Specifications of JSP
Ans. There are three specifications present for JSP namely
1. By Default, JSP extends HTTP.
2. By Default, all translated servlets extends a class called HTTP JSP Base.
3. By Default, all translated servlets are stored in work folder of Apache Tomcat Server.
=> Scriptlet:- Area to write Java Codes on a JSP file.
=> Expression:- Used to represent or print Java Codes(Output).
=> Q. (M.M.M.Imp.) Implicit Objects of JSP
Ans. There are 9 implicit objects present in JSP namely.
1. Request 4. Session 7. Out
2. Response 5. Application 8. Exception
3. Config 6. Page 9. Page Context
=> (M.M.M.Imp.) The default scope of JSP is page.
=> (M.M.Imp.) Criteria for JSP
* There are 3 criterias present for JSP namely.
1. We cannot write one JSP element inside another JSP element.
2. We cannot write any HTML code inside the JSP element.
3. We can write any JSP element for any no. of times.
=> (M.M.M.Imp.) By Default, JSP is also MultiThreaded but it can be made Single Threaded.
<%@ Page is Thread Safe =”False” %>
=> Q. Why is JSP used instead of HTML to give presentation logic?
Ans. JSP is used instead of HTML for two reasons
1. Since JSP is Dynamic resource.
2. Is Code Simplification.
=> MetaData
* Data about the data is known as MetaData.
Ex.- Variables, ColumnNames, TableNames
* There are two types of metadata present namely.
1. Database MetaData=> Used to deal with DB whenever there is lack of information w.r.t. DB.
2. ResultSet MetaData=> Used to deal with tables whenever there is lack of information w.r.t. the
datas present in the table.

You might also like