• No results found

Callable Statement (Use prepareCall) : //For Stored procedure Callable statement, where sql is stored procedure.

In document Complete Java and J2EE By VENKI (Page 40-44)

What Class.forName will do while loading drivers?

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.

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

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

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 SERVLETS 1. What is the servlet?

Servlets are modules that extend request/response-oriented servers, such as Java- enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

-Servlets are used to enhance and extend the functionality of Webserver. -Servlets handles Java and HTML separately.

In document Complete Java and J2EE By VENKI (Page 40-44)