Jsp Tutorial Home

Jsp Home

JSP Resources

Community

Site

The database interaction with the JSP page is similar to the core JDBC interaction. The complete JDBC code for the database interaction is to be written in the scriptlet tags. The following example shows the process of database handling with the JSP page. The following example will display the total hit for the current page and update the counter in the database.


<%@page import="java.sql.*" %>
<%
    int hitCount=0;
    try{
        Class.forName("org.gjt.mm.mysql.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
            Statement statement = connection.createStatement();
            int changed = statement.executeUpdate("update counters set hitCount = hitCount + 1 " +"where page like '" + request.getRequestURI() + "'");
         if (changed == 0) statement.executeUpdate("insert counters(page) values('" + request.getRequestURI() + "')");
            ResultSet rs = statement.executeQuery("select hitCount from counters where page like '" + request.getRequestURI() + "'");
        rs.next();
         hitCount = rs.getInt(1);
        }catch(Exception e ){
        }finally{
            statement.close();
            connection.close();
        }
    out.println("The hit count is " +hitCount );
%>


Output:-


The page prints "The hit count is 5" as output.

                    

Copyright © 2010 VisualBuilder. All rights reserved