ConnectionObject.setAutoComit();
after any updates through the program cannot be
effected to the database.We have commit the transctions .For this puprpose we
can set AutoCommit flag to Connection Object.
What are the three statements in JDBC &
differences between them
which is used to run simple sql statements like
select and update
2. PrepareStatment is used to run Pre compiled
sql.
3. CallableStatement is used to execute the stored
procedures.
What is stored procedure. How do you create stored
procedure ?
Stored
procedures is a group of SQL statements that performs a logical unit and
performs a particular task.
Stored
procedures are used to encapsulate a set of operations or queries to execute on
data.
Stored
Procedure is a stored program in database, PL/SQL program is a Stored
Procedure. Stored Procedures can be called from java by CallableStatement
A
precompiled collection of SQL statements stored under a name and processed as a
unit.
Stored procedures can:
1.Accept input parameters and return multiple
values in the form of output parameters to the calling procedure or batch.
2.Contain programming statements that perform
operations in the database, including calling other procedures.
3.Return a status value to a calling procedure or
batch to indicate success or failure (and the reason for failure).
What are batch updates?
Batch Update facility allows multiple update
operations to be submitted to a database for processing at once. Using batch
updates will improve the performance.
What is the difference between Resultset and Rowset
A RowSet is a disconnected, serializable version of
a JDBC ResultSet.
The RowSet is different than other JDBC interfaces
in that you can write a RowSet to be vendor neutral. A third party could write
a RowSet implementation that could be used with any JDBC-compliant database.
The standard implementation supplied by Sun uses a ResultSet to read the rows
from a database and then stores those rows as Row objects in a Vector inside
the RowSet. In fact, a RowSet implementation could be written to get its data
from any source. The only requirement is that the RowSet acts as if it was a
ResultSet. Of course, there is no reason that a vendor couldn't write a RowSet
implementation that is vendor specific.
The
standard implementations have been designed to provide a fairly good range of
functionality. The implementations provided are:
CachedRowSetImpl - This is the implementation
of the RowSet that is closest to the definition of RowSet functionality that we
discussed earlier. There are two ways to load this RowSet. The execute ( )
method will load the RowSet using a Connection object. The populate( ) method
will load the RowSet from a previously loaded ResultSet.
WebRowSetImpl - This is very similar to the
CachedRowSetImpl (it is a child class) but it also includes methods for
converting the rows into an XML document and loading the RowSet with an XML
document. The XML document can come from any Stream or Reader/Writer object.
This could be especially useful for Web Services.
JdbcRowSetImpl - This is a different style of
implementation that is probably less useful in normal circumstances. The
purpose of this RowSet is to make a ResultSet look like a JavaBean. It is not
serializable and it must maintain a connection to the database.
The remaining two implementations are used with the
first three implementations:
FilteredRowSetImpl - This is used to filter
data from an existing RowSet. The filter will skip records that don't match the
criteria specified in the filter when a next() is used on the RowSet.
JoinRowSetImpl - This is used to simulate a
SQL join command between two or more RowSet objects.
What are the steps for connecting to the database
using JDBC
Using DriverManager:
1. Load the driver class using
class.forName(driverclass) and class.forName() loads the driver class and
passes the control to DriverManager class
2. DriverManager.getConnection() creates the
connection to the databse
Using
DataSource.
DataSource is used instead of DriverManager in
Distributed Environment with the help of JNDI.
1. Use JNDI to lookup the DataSource from Naming
service server.
- DataSource.getConnection method will return
Connection object to the database
What is Connection Pooling ?
Connection pooling is a cache of data base connections that is
maintained in memory , so that the connections may be reuse.
Connection pooling is a place where a set of connections are kept and
are used by the different programers with out creating conncections to the
database(it means there is a ready made connection available for the
programmers where he can use). After using the connection he can send back that
connection to the connection pool. Number of connections in connection pool may
vary.
How do you implement Connection Pooling
Connection Pooling can be implemented by the
following way.
*
A javax.sql.ConnectionPoolDataSource interface that serves as a resource
manager connection factory for pooled java.sql.Connection objects. Each
database vendors provide the implementation for that interface.
For example, the oracle vendors implementation is as follows:
oracle.jdbc.pool.oracleConnectionPoolDataSource
Class.
- A javax.sql.PooledConnection interface
encapsulates the physical connection for the database. Again, the vendor
provides the implementation.
What Class.forName( ) method will do
Class.forName() is used to load the Driver class which is used to
connect the application with Database. Here Driver class is a Java class
provided by Database vendor.
What is the difference between JDBC 1.0 and JDBC
2.0
The JDBC
2.0 API includes many new features in the java.sql package as well as the new
Standard Extension package, javax.sql. This new JDBC API moves Java
applications into the world of heavy-duty database computing. New features in
the java.sql package include support for SQL3 data types, scrollable result
sets, programmatic updates, and batch updates. The new JDBC Standard Extension
API, an integral part of Enterprise JavaBeans (EJB) technology, allows you to
write distributed transactions that use connection pooling, and it also makes
it possible to connect to virtually any tabular data source, including files
and spread sheets.
The JDBC
2.0 API includes many new features like
- Scrollable
result sets
- Batch
updates
- Connection
Pooling
- Distributed
transactions
- set
autocomit ( )
What is JDBC?
JDBC is a layer of abstraction that allows users to
choose between databases. It allows you to change to a different database
engine and to write to a single API. JDBC allows you to write database
applications in Java without having to concern yourself with the underlying
details of a particular database.
What are the two major components of JDBC?
One implementation interface for database
manufacturers, the other implementation interface for application and applet
writers.
What is JDBC Driver interface?
The JDBC
Driver interface provides vendor-specific implementations of the abstract
classes provided by the JDBC API. Each vendors driver must provide
implementations of the java.sql.Connection,Statement,PreparedStatement,
CallableStatement, ResultSet and Driver.
What are the common tasks of JDBC?
Create an instance of a JDBC driver or load JDBC
drivers through jdbc.drivers
Register a driver
Specify a database
Open a database connection
Submit a query
Receive results
What packages are used by JDBC?
There are 8 packages: java.sql.Driver,
Connection,Statement, PreparedStatement, CallableStatement, ResultSet,
ResultSetMetaData, DatabaseMetaData.
What are the flow statements of JDBC?
A URL string
-->getConnection-->DriverManager-->Driver-->Connection-->Statement-->executeQuery-->ResultSet.
1). Register the Driver
2) load the Driver
3)get the connection
4) create the statement
5) Execute the query
6) fetch the results with ResultSet
What are the steps involved in establishing a
connection?
This involves two steps: (1) loading the driver and
(2) making the connection.
How can you load the drivers?
Loading the driver or drivers you want to use is
very simple and involves just one line of code. If, for example, you want to
use the JDBC-ODBC Bridge driver, the following code will load it:
Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class
name to use. For instance, if the class name is jdbc.DriverXYZ , you would load
the driver with the following line of code:
E.g.
Class.forName("jdbc.DriverXYZ");
What Class.forName will do while loading drivers?
It is used to create an instance of a
driver and register it with the
DriverManager. When you have loaded a driver, it is available for making
a connection with a DBMS.
How can you make the connection?
In establishing a connection is to have the
appropriate driver connect to the DBMS. The following line of code illustrates
the general idea:
E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url,
"Fernanda", "J8");
How can you create JDBC statements?
A
Statement object is what sends your SQL statement to the DBMS. You simply
create a Statement object and then execute it, supplying the appropriate
execute method with the SQL statement you want to send. For a SELECT statement,
the method to use is executeQuery. For statements that create or modify tables,
the method to use is executeUpdate. E.g. It takes an instance of an active
connection to create a Statement object. In the following example, we use our
Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();
How can you retrieve data from the ResultSet?
First
JDBC returns results in a ResultSet object, so we need to declare an instance
of the class ResultSet to hold our results. The following code demonstrates
declaring the ResultSet object rs.
E.g.
ResultSet rs = stmt.executeQuery("SELECT
COF_NAME, PRICE FROM COFFEES");
Second:
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet
object rs , so getString will retrieve (get) the value stored in the column
COF_NAME in the current row of rs
What are the different types of Statements?
1. Create
Statement : For Simple statement
used for static query.
2.Prepared
Statement :For a runtime / dynamic query .Where String is a dynamic
query you want to execute
3. Callable
Statement (Use prepareCall) : //For Stored procedure Callable statement,
where sql is stored procedure.
try
{
Connection conn = DriverManager.getConnection("URL",'USER"."PWD");
Statement stmt = conn.createStatement();
PreparedStatement pstmt =
conn.prepareStatement(String sql);
CallableStatement cstmt = conn.prepareCall(String
sql);
}
catch (SQLException ee)
{
ee.printStackTrace();
}
Don't forget all the above statements will throw
the SQLException, so we need to use try catch for the same to handle the
exception.
How can you use PreparedStatement?
This special type of statement is derived from the
more general class, Statement. If you want to execute a Statement object many
times, it will normally reduce execution time to use a PreparedStatement object
instead. The advantage to this is that in most cases, this SQL statement will
be sent to the DBMS right away, where it will be compiled. As a result, the
PreparedStatement object contains not just an SQL statement, but an SQL
statement that has been precompiled. This means that when the PreparedStatement
is executed, the DBMS can just run the PreparedStatement 's SQL statement
without having to compile it first.
E.g. PreparedStatement
updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
How to call a Stored Procedure from JDBC?
The first step is to create a CallableStatement
object. As with Statement an and PreparedStatement objects, this is done with
an open Connection object. A CallableStatement object contains a call to a
stored procedure;
E.g.
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
How to Retrieve Warnings?
SQLWarning
objects are a subclass of SQLException that deal with database access warnings.
Warnings do not stop the execution of an application, as exceptions do; they
simply alert the user that something did not happen as planned. A warning can
be reported on a Connection object, a Statement object (including
PreparedStatement and CallableStatement objects), or a ResultSet object. Each
of these classes has a getWarnings method, which you must invoke in order to
see the first warning reported on the calling object
E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
while (warning != null) {
System.out.println("Message: " +
warning.getMessage());
System.out.println("SQLState: " +
warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the
ability to update rows in a result set using methods in the Java programming
language rather than having to send an SQL command. But before you can take
advantage of this capability, you need to create a ResultSet object that is
updatable. In order to do this, you supply the ResultSet constant
CONCUR_UPDATABLE to the createStatement method.
E.g.
Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM
COFFEES");
SERVLETS
Web
Components
•Servlets
•Java Server Pages (JSP)
•Tags and Tag Libraries
What’s a Servlet?
•Java’s answer to CGI programming
•Program runs on Web server and builds pages on the fly
•When would you use servlets?
–Data
changes frequently e.g. weather-reports
–Page
uses information from databases e.g. on-line stores
–Page
is based on user-submitted data e.g search engines
–Data
changes frequently e.g. weather-reports
–Page
uses information from databases e.g. on-line stores
–Page
is based on user-submitted data e.g search engines
Servlet Class Hierarchy
•javax.servlet.Servlet
–Defines
methods that all servlets must implement
•init()
•service()
•destroy()
•javax.servlet.GenericServlet
–Defines
a generic, protocol-independent servlet
•javax.servlet.http.HttpServlet
–To
write an HTTP servlet for use on the Web
•doGet()
•doPost()
•javax.servlet.ServletConfig
–A servlet configuration object
–Passes information to a servlet during
initialization
•Servlet.getServletConfig()
•javax.servlet.ServletContext
–To communicate with the servlet container
–Contained within the ServletConfig object
•ServletConfig.getServletContext()
•javax.servlet.ServletRequest
–Provides client request information to a
servlet
•javax.servlet.ServletResponse
–Sending a response to the client
Basic
Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello World extends
HttpServlet {
//
Handle get request
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// request – access
incoming HTTP headers and HTML form data
//
response - specify the HTTP
response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter(); //out - send content to browser
out.println("Hello World");
}
}
Servlet
Life Cycle
•Loading and Instantiation
•Initialization
•Request Handling
•End of Service
Session
Tracking
•Typical scenario – shopping cart in online
store
•Necessary because HTTP is a "stateless"
protocol
•Session Tracking API allows you to
–look
up session object associated with current request
–create
a new session object when necessary
–look
up information associated with a session
–store
information in a session
–discard
completed or abandoned sessions
Session
Tracking API - I
•Looking up a session object
–HttpSession
session = request.getSession(true);
–Pass true to create a new session
if one does not exist
•Associating information with session
–session.setAttribute(“user”,request.getParameter(“name”))
–Session attributes can be of any type
•Looking up session information
–String
name = (String) session.getAttribute(“user”)
Session
Tracking API - II
•getId : –the unique
identifier generated for the session
•isNew : –true if the
client (browser) has never seen the session
•getCreationTime : –time in
milliseconds since session was made
•getLastAccessedTime : –time in
milliseconds since the session was last sent from client
•getMaxInactiveInterval : –# of seconds
session should go without access before being invalidated . –negative value indicates that session
should never timeout
Javax.Servlet
Interface Classes
Servlet Genericservlet
ServletRequest ServletInputStream
ServletResponce
ServletOutputStream
ServletConfig
ServletException
ServletContext
UnavailableException
SingleThreadModel -
Javax.Servlet.Http
Classes
HttpServletRequest Cookie
HttpServletResponse
HttpServlet
HttpSession
HttpSessionBindingEvent
HttpSessionContext
HttpUtils
HttpSessionBindingListener -
Exceptions
ServletException
UnavailableException
No comments:
Post a Comment