• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Servlet

MySql DIVISION Function in Java Servlet

By Dinesh Thakur

This function will also return the divided value from two expressions with a sign of division (/).

The first i made a database named ‘dbase’ within the reference of mySql(php myAdmin). Then after i import all java packages from java library as program need. Here i made a class named ‘MySqlDIVISIONFunction’ which extends ‘HttpServlet’. I use service()Method that will help to getting the request from doGet()Method for output on web browser. Then i loaded all the required Drivers that will help to accessing Database. After then i declare variable first i use ‘connection’ variable that will create a link between database and the actual code (frontend and the backend).other variable is ‘ResultSet’ that will help to fetch value from the columns and rows as required query. The next variable is ‘preparedStatement’ that will use to executing the selected Query like executeQuery () as (Select 60 / 20).I use doGet()Method in last instance that will bring the output on web browser.

While getting output on the web browser i use ‘HTML’ code and tags which will present the output in tabular form.

 import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDIVISIONFunction extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
      {
         rp.setContentType("text/html");
         PrintWriter disp = rp.getWriter();
         String driver = "com.mysql.jdbc.Driver";
         String url = "jdbc:mysql://localhost/dbase";
         String uid = "root";
         String psw = "root";
         Connection con=null;
         PreparedStatement ps = null;
         ResultSet rs;
         try
          {
              Class.forName(driver);
              con = DriverManager.getConnection(url,uid,psw);
              ps=con.prepareStatement("Select 60/20");
              rs = ps.executeQuery();
              String title = "Using DIVISION Function";
              String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
              while(rs.next())
                  {
                      String val = rs.getString(1);
                   disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
                  }     
          }           
                   catch(Exception e) 
                       {
                         e.printStackTrace();
                       }
                         disp.close();
      }
                           public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                               {
                                 doGet(rq,rp);
                               }
 }
Web.xml
 
<servlet>
   <servlet-name>MySqlDIVISIONFunction</servlet-name>
   <servlet-class>MySqlDIVISIONFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDIVISIONFunction</servlet-name>
   <url-pattern>/MySqlDIVISIONFunction</url-pattern>
</servlet-mapping>

MySql DIV Function in Java Servlet

By Dinesh Thakur

This function will return divided value from two expressions. The first i made a database named ‘dbase’ within the reference of mySql(php myAdmin). Then after i import all java packages from java library as program need. Here i made a class named ‘MySqlDIVFunction’ which extends ‘HttpServlet’.i use service()Method that will help to getting the request from doGet()Method for output on web browser.

Then i loaded all the required Drivers that will help to accessing Database. After then i declare variable first i use ‘connection’ variable that will create a link between database and the actual code(frontEnd and the backEnd).other variable is ‘ResultSet’ that will help to fetch value from the columns and rows as required query. The next variable is ‘preparedStatement’ that will use to executing the selected Query like executeQuery as (Select 60 DIV 20). I use doGet()Method in last instance that will bring the output on web browser.

To get output on web browser in tabular form i use ‘HTML’ tags in it.

 import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDIVFunction extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
      {
          rp.setContentType("text/html");
          PrintWriter disp = rp.getWriter();
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost/dbase";
          String uid = "root";
          String psw = "root";
          Connection con=null;
          PreparedStatement ps = null;
          ResultSet rs;
          try
            {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("Select 60 DIV 20");
                rs = ps.executeQuery();
              String title = "Using DIV Function";
                String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
             "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
               while(rs.next())
                  {
                       String val = rs.getString(1);
                     disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
                  }     
            }         
                     catch(Exception e) 
                        {
                          e.printStackTrace();
                        }
                          disp.close();
        }
                            public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                 {
                                  doGet(rq,rp);
                                 }
 }
Web.xml
 
<servlet>
   <servlet-name>MySqlDIVFunction</servlet-name>
   <servlet-class>MySqlDIVFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDIVFunction</servlet-name>
   <url-pattern>/MySqlDIVFunction</url-pattern>
</servlet-mapping>

MySql DEGREES Function in Java Servlet

By Dinesh Thakur

This Function will return the degree value from radian expression. I made a database first named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the required java packages from the java library. Here after i made a class named ‘MySqlDEGREESFunction’ which extends ‘HttpServlet’ Completely.

 

Then i use service()Method that will help to getting request from the doGet()Method for output. After that i loaded all the required drivers that are useful for database accessing. Then i declare the mandatory drivers like i use ‘connection’ variable that will use to create a link between database and java code. After that i declare ‘resultSet()that will use to get value from the columns and rows as selected table. Here after i use to declare ‘preparedStatement’ that will act as to executing selected query like executeQuery() as (Select DEGREES(’60’)). In the last i use doGet()Method which will bring the output on the web browser.

I use ‘HTML’ code and tags that will bring the output in tabular form on the web browser.

 import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDEGREESFunction extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
          rp.setContentType("text/html");
          PrintWriter disp = rp.getWriter();
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost/dbase";
          String uid = "root";
          String psw = "root";
          Connection con=null;
          PreparedStatement ps = null;
          ResultSet rs;
          try
            {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("Select DEGREES('60')");
                rs = ps.executeQuery();
           String title = "Using DEGREES Function";
               String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
           disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
                while(rs.next())
                  {
                      String val = rs.getString(1);
                  disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
                  }     
            }    
                  catch(Exception e) 
                      {
                     e.printStackTrace();
                      }
                     disp.close();
     }
                          public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                               {
                                doGet(rq,rp);
                               }
 }
Web.xml
<servlet>
   <servlet-name>MySqlDEGREESFunction</servlet-name>
   <servlet-class>MySqlDEGREESFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDEGREESFunction</servlet-name>
   <url-pattern>/MySqlDEGREESFunction</url-pattern>
</servlet-mapping>

MySql Distnict() Function Java Servlet

By Dinesh Thakur

This function will use to wipe Duplicate columns and rows. The first i made a table named ‘dept’ with required fields and the values into a database named ‘dbase’ within the reference of mySql(php myAdmin). Then after i import all java packages from java library as program need. Here i made a class named ‘MySqlDistnictJavaServlet’ which extends ‘HttpServlet’.i use service()Method that will help to getting the request from doGet()Method for output on web browser.

Then i loaded all the required Drivers that will help to accessing Database. After then i declare variable first i use ‘connection’ variable that will create a link between database and the actual code (frontEnd and the backEnd).other variable is ‘ResultSet’ that will help to fetch value from the columns and rows as required query. The next variable is ‘preparedStatement’ that will use to executing the selected Query like executeQuery as (SELECT DISTINCT dept_id FROM dept). I use doGet()Method in last instance that will bring the output on web browser.

On the web browser while getting output on it i use ‘HTML’ code and tag that will bring the output in tabular form.

 import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDistnictJavaServlet extends HttpServlet
 {
      public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
             {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("SELECT DISTINCT dept_id FROM dept");
                rs = ps.executeQuery();
              String title = "Using Distinct Function";
                String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Departments Id</th>\n"+ "</body> </html>");
                while(rs.next())
                  {
                       int d_id = rs.getInt("dept_id");
                    disp.println("<tr><td align=\"center\">" + d_id +  "</td></tr>" );  
                  }      
            }         
                    catch(Exception e) 
                       {
                         e.printStackTrace();
                       }
                         disp.close();
     }
                            public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                {
                                 doGet(rq,rp);
                                }
}
Web.xml
<servlet>
   <servlet-name>MySqlDistnictJavaServlet</servlet-name>
   <servlet-class>MySqlDistnictJavaServlet</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDistnictJavaServlet</servlet-name>
   <url-pattern>/MySqlDistnictJavaServlet</url-pattern>
</servlet-mapping>

MySql DayOfYear() function in Java Servlet

By Dinesh Thakur

This function will return the Day of Year (1 to 365). First i made a database named ‘dbase’ within the reference of mySql(php myAdmin) with required fields and values in it. Then according to need of  program i import all the java packages from the java library. I create a class named ‘MySqlDayOfYear’ which extends ‘HttpServlet’. Then i use serviceMethod() that will bring the request from doGet()Method for output on web browser.

 

After using serviceMethod() I loaded all the required Drivers mandatory for database accessing. Here after i declare variables like first i use ‘connection’ this will use to create a link between database and the java code. Then i use ‘resultSet’ this use to get the value from selected columns and rows. And the other one i use is ‘preparedStatement’ this will use to executing the selected Query like executeQuery() as (Select DAYOFYEAR(‘2014-05-31’)). I use doGet()Method for output on the web browser.

I use ‘HTML’ code and tags to bring output on the web browser in tabular form.

import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDayOfYear extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
             {
                 Class.forName(driver);
                 con = DriverManager.getConnection(url,uid,psw);
                 ps=con.prepareStatement("Select DAYOFYEAR('2014-05-31') AS dy");
                 rs = ps.executeQuery();
             String title = "Using Day Of Year Function";
                 String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
            disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Day</th>\n"+ "</body> </html>");
                while(rs.next())
                   {
                       String curr = rs.getString(1);
                  disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                   }     
             }   
                  catch(Exception e) 
                           {
                     e.printStackTrace();
                       }
                     disp.close();
     }
                          public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                              {
                            doGet(rq,rp);
                              }
}
Web.xml
<servlet>
   <servlet-name>MySqlDayOfYear</servlet-name>
   <servlet-class>MySqlDayOfYear</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDayOfYear</servlet-name>
   <url-pattern>/MySqlDayOfYear</url-pattern>
</servlet-mapping>

MySql DayOfWeek Function in Java Servlet

By Dinesh Thakur

This function will return the value as Day Of week (1-7). first i made a database named ‘dbase’ within the reference of mySql(php myAdmin).i import all the required java packages from java library according to requirement of program. Then i made a class named ‘MySqlDayOfWeek’ which extends ‘HttpServlet’. Then after i use service()Method that will getting request from the doGet() for output on the web browser. Then after i loaded all the required drivers for database accessing.

Here i need to declare some variable which are mandatory for database using like i declare ‘connection’ this will be responsible for the create a link or bridge between the database and the java code. Then i declare ‘resultSet’ this variable will use to get the value from the selected column and rows. The last one will be the ‘preparedStatement’ that will use to executing the selected query like executeQuery() as (Select DAYOFWEEK(‘2014-05-31’)).here i use the doGet()Method for the output on web browser.

I use ‘HTML’ code and tags in last move to get output in tabular form on the web browser.

 import java.io.IOException; 
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDayOfWeek extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
            {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("Select DAYOFWEEK('2014-05-31') AS dw");
                rs = ps.executeQuery();
             String title = "Using Day Of Week Function";
               String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Day</th>\n"+ "</body> </html>");
                while(rs.next())
                  {
                     String curr = rs.getString(1);
                   disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                  }     
           }          
                   catch(Exception e) 
                      {
                         e.printStackTrace();
                      }
                         disp.close();
      }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
 }
Web.xml
 
<servlet>
   <servlet-name>MySqlDayOfWeek</servlet-name>
   <servlet-class>MySqlDayOfWeek</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDayOfWeek</servlet-name>
   <url-pattern>/MySqlDayOfWeek</url-pattern>
</servlet-mapping>

Accessing Metadata in Java Servlet

By Dinesh Thakur

To make operations on the database we should know the data formats of the database. When using a ResultSet it is possible to access metadata for the data returned from the query. To obtain an object which encapsulates this metadata, use the method getMetaData () from the ResultSet class. This method returns an object of the ResultSetMetaData class and allows us to determine the number and type of columns.

The following is an example of how to use ResultSetMetaData:

String sql= "select * from Emp_info";
ResultSet rs = stmt.executeQuery (sql);
ResultSetMetaData metaData = rs.getMetaData ();
int column Count = metaData.getColumnCount ();
for (int count=1; count <= columnCount; count++)
{
     String columnType = metaData.getColumnTypeName (count);
     String column Name = metaData.getColumnName (count);
     System.out.println ("Column name:" + columnName + "Type:" + columnType);
}
The output of this appears as follows:
Column name: emp no Type: varchar
Column name: emp name Type: varchar
Column name: designation Type: varchar
Column name: date_of_joining Type: date
Column name: salary_in_rupees Type: float

Methods in the class ResultSetMetadata

 

Table lists the methods in the class ResultSetMetadata, with a short description.

                               Table Methods in the class ResultSetMetadata.

Method Description
public int getColumnCount () throws
SQLException;
Returns the number of columns in the given ResultSet object.
public boolean isSearchable (int column) throws SQLException;Returns whether the specified column can use the where clause.
public String getColumnLabel (int column) throws SQLException;Returns a string, which is a column label. Column label is the alias name given to the table field when
retrieving.
public String getColumnName (int column)
throws SQLException;
Returns the string, which specifies the column name.
public String getTableName (int column) throws SQLException;Returns the table name of the designated column.
public int getColumnType (int column) throws SQLException;Returns the designated column type in the forms of integer, which specified in Types class.
public String getColumnTypeName (int column) throws SQLException;Returns string, which specifies the data type of the column.

The class DatabaseMetadata

Like ResultSetMetaData we can get metadata for databases. The DatabaseMetaData class is used for obtaining database metadata. Like ResultsetMetaData, DataBaseMetaData also contains several methods which describe the database. Here is an example which uses DatabaseMetaData to retrieve a list of tables from the database:

DatabaseMetaData dbmd = dbCon.getMetaData ();
ResultSet rs = dbmd.getTables (null, null, "*", null);
while (rs.next ())
System.out.println (rs.getString (1) +" "+ rs.getString (3));

The above code displays the catalogue name and table name. The output is the following:

Catalogue                                                 Table-Name

/home/matt/classes/Exercises           PSYCHICVAMPIRES

/home/matt/classes/Exercises           BUSINESS CONTACTS                                               

/home/matt/classes/Exercises           SOCIAL CONTACTS

                                                         

The getTables () method of the class DataBaseMetaData returns the object of ResultSet with ten columns (which describe the table).

There are many database metadata methods used in the programming Some of the commonly used database metadata methods are listed in Table.

                 Table List of some methods in the class DataBaseMetaData.

Method

Description

ResultSet get Catalogs ()

Retrieves the catalogue names available in this database.

ResultSet getProcedureColumns (String

catalog, String schemaPattern, String

procedure NamePattern, String

columnNamePattern)

Retrieves a description of the given catalogue’s stored procedure parameter and result columns.

ResultSet getProcedures (String

catalog, String schemaPattern, String

procedureNamePattern)

Retrieves a description of the stored procedures available in the given catalogue procedures available in the given catalogue.

ResultSet getSchemas ()

Retrieves the schema names available in this database.

ResultSet getUDTs (String catalog, String

schemaPattern,String typeNamePattern,

int [] types)

Retrieves a descriptionof the user-defined types(UDTs) defined in a particular schema.

boolean supportsBatchUpdates ()

Retrieves whether this database supports batch updates.

Mapping Database Types to Java

By Dinesh Thakur

The package java.sql contains a number of data types for compatibility with SQL database types. Some of these types are shown in Table.

Java format types

Although, not directly related to JDBC, the package java.text contains a number of classes which can be used for formatting output. The classes provided here include those to format java.util.Date and floating point numbers for display output.

Here is an example of using the class DateFormat to format a date for display purposes:

Calendar cal = Calendar.getInstance (TimeZone.getTimeZone (“AET”),

                                                                           new Locale (“AU”, “EN”));

Date aDate = cal.getTime ();

DateFormat df = DateFormat.getDateTimeInstance ();

df.setTimeZone (TimeZone.getTimeZone (“AET”));

String date = df.format (aDate);

System.out.println (“Date is:” + date);

Note that in the versions of Java prior to Java 2, simply obtaining a java.util.Date object does not work, as there is a problem with localities outside the United States. Therefore, some of these methods have been deprecated, and the method Calendar is to be used instead.

                                             Table Java and SQL data types.

Java Type

SQL Types

Description

String

CHAR

VARCHAR

LONGVARCHAR

Single character

String of characters of variable length.

Very long strings of the variable length.

int

INTEGER

32-bit values

Double

FLOAT

DOUBLE

15-bit mantissa precision

byte [ ]

BINARY

VARBINARY

LONGVARBINARY

Binary data (array of binary values) ranging up to MultiMegabytes

java.sql.Date

DATE

Date: yyyy-mm-dd

java.sql.Time

TIME

Time: hh-mm-ss

java.sql.Timestamp

TIMESTAMP

A more precise time

 

Handling Exceptions in Servlet

By Dinesh Thakur

Java provides two levels of error conditions at which to handle exceptions thrown by JDBC statements: SQLException and SQLWarning. The SQLException class provides information on the errors that have occurred during database access. This information consists of nature of error, error message, SQL state and vendor-specific information. If SQLExceptions are not handled, the program will terminate. The SQLWarning conditions are sub-classes of the SQLException condition: these provide information on the database access warnings. These can be ignored.

Constructors of the SQLException class are shown below:

public SQLException (String reason, String sqlstate, int vendorcode);

public SQLException (String reason, String sqlstate);

public SQLException (String reason);

public SQLException ();

The SQLException class accepts three parameters: reason, sqlstate and vendorcode. The parameter reason gives the description of the exception. The second parameter, sqlstate, explains the XOPEN code for identifying the exception and the third one, vendor code, is the vendor-specific code for the exception.

In general we use three methods of the SQLException. These are listed in Table.

                            Table Methods of the class SQLException.

Name of method

Description

public int getErrorCode ()

Returns the integer value containing the vendor-specific code.

public SQLException getNextException ()

Returns the next exception in the exception

chain.

public String getSQLState ()

Returns the string containing the SQL state.

Another exception thrown by the JDBC is the ClassNotFoundException. This exception is thrown by the static method Class.forName () at the time of loading the driver class. If the driver class is not found then this exception is thrown.

The objects of classes Connection, Statement and ResultSet also throw SQLWarning exceptions. The constructors for the SQLWarning class are the same as those of the SQLException class.

How to Commit and Rollback Transactions in Servlet

By Dinesh Thakur

When a database is updated with each Statement object, by default, it will automatically commit the changes (permanently) to the database immediately. In general, to complete a transaction, it is required that one or more statements be executed. Thus, there are situations where a commit statement is needed after execution of more than one statement. In Java, the Connection object performs transaction control. The Connection object provides a method setAutoCommit (boolean value) to specify whether a transaction (or a set of transactions) should commit automatically or manually. By default, it is set to auto-commit mode. The syntax for this is the following:

dbcon.setAutoCommit (true);

This auto-commit feature can be turned off with the statement:

dbcon.setAutoCommit (false);

To commit a transaction, when the auto-commit feature is off, the statement to be used is the following:

dbcon.commit ();

If a transaction is to be rolled back at any point, this can be specified as follows:

dbcon.rollback ();

In general, the rollback statement is used in exception handlers to recover from errors that may have occurred during execution of a transaction.

 

                                           Table Methods of the class SQLException.

Name of method

Description

public int getErrorCode ()

Returns the integer value containing the vendor-specific code.

public SQLException getNextException ()

Returns the next exception in the exception

chain.

public String getSQLState ()

Returns the string containing the SQL state.

The version JDBC 3.0 API allows the programmer to create save points to be specified during a transaction, after which a rollback may be issued: this transaction can rollback the changes that have taken place after the save point.

JDBC Processing Queries

By Dinesh Thakur

Java database connectivity defines a set of API objects and methods to communicate with databases. In the process of communicating with databases, a Java program does the following:

• Opens a connection to a database

• Makes a Statement object

• Passes SQL statements to the DBMS through the Statement Object, and

• Retrieves the results of the SQL statements, along with information about the result sets.

There are three different ways of constructing and executing SQL statements in JDBC. They use the following classes:

• Statement : This class allows the execution of static SQL command in a string format.

• PreparedStatement :    This class allows repeated execution of a compiled statement. We can also use it to execute a parameter-less stored procedure.

• CallableStatement :      This class allows executing the stored procedures and takes advantage of optimization by the database system.

PreparedStatement and CallableStatement are the sub-classes of the Statement class.

The Statement class

A class by name Statement is created using the createStatement () method of the Connection class, which returns a Statement object. The syntax is the following:

Statement stmt = dbCon.createStatement () ;

The execution of the above statement gives the instance stmt of the Statement object but it does not have any SQL statement to pass on to the DBMS at that point of time.

The Statement class is used to build SQL statements for database operations such as creation, updation, retrieval and deletion. Methods of the Statement class take a parameter string containing the SQL statement to be executed.

There are three possible Statement methods which can be used to execute an SQL statement string:

• executeQuery (String sql) :  This method is used for SELECT statements. Returns the ResultSet object. The result set consists of the rows returned by the select statement.

• executeUpdate (String sql) :  This method is used for SQL statements such as INSERT, UPDATE or DELETE, which will update the database. It returns an integer value, which specifies number of rows affected. This statement can also be used for executing DDL statements (for creating, altering and deleting tables)

• execute (String sql) : This method is used when the SQL statement may be an update or query. (This statement can be used in place of executeQuery() as well as executeUpdate().)

The following is an example showing how to execute a query:

Statement stmt = dbCon.createStatement ();

stmt.executeQuery (“select *from Emp_info”);

Alternately, it can also be written as follows:

Statement stmt = dbCon.createStament ();

String sql = “select * from Emp_info”;

stmt.executeQuery (sql);

The Statement object stmt that was created can be (re)used more than once for different SQL statements. Some of the methods in the statements class are listed in Table.

Data can be inserted or updated with SQL insert and update statements using the method executeUpdate. The following example shows to insert data into the Emp_info table:

Statement stmt = dbCon.createStatement();

String sql=”insert into Emp_info values (1223,’raja’,’technicalwriter’,5000)”;

stmt.executeUpdate (sql);

                                      TableMethods In the statement class.

public void addBatch (String sql) throws SQLException;

This method adds the SQL command with the batch and this command is executed when the executeBatch (), method is called.

public void clearBatch () throws SQLException;

This method clears the current collection of the SQL commands with in the batch.

public void c1ose () throws SQLException;

This method releases all the databases and JDBC resources to the Statement object.

public int [ ] executeBatch( ) throws

SQLException;

This executes all the SQL commands added to the batch and returns the integer array specifying number of rows affected by the command execution. It throws SqlException and BatchUpdateException.

public connection getConnection () throws SQLException;

It returns the Connection object, that produced this Statement object.

public int getFetchDirection () throws SQLException;

This returns the direction of the fetch from the database.

public int getFetchSize ()throws

SQLException;

This returns the number of rows fetched from the database (for each fetch) to produce ResultSet object.

public static void setFetchDirection (int value) throws SQLException;

It gives the hint to the driver as to the direction in which the database is fetched to produce the ResultSet.

public void setFetchSize (int rows) throws

SQLException;

This sets the number of rows that are to be fetched into the ResultSet object.

public void setMaxRows (int max) throws

SQLException;

This sets the limit for the maximum number of rows that any ResultSet object can contain to the given number.

Note that if an SQL statement does not fit in one line, it can be split into strings concatenated by a plus sign (+). Otherwise, the statement can not be compiled. Also note that there is a single space after the name of the table. The programmer must be careful while concatenating strings so that after concatenation it gives a complete SQL statement.

An example that shows how to update the Emp _info table is the following:

stmt.executeUpdate (“update Emp_Info set designation = ‘Analyst’ where emp no = 2371);

The executeUpdate () method returns the number of rows that are affected by the SQL statement. For example, the following statement assigns the return value of executeUpdate to the variable n. This information is useful to find how many rows have been actually updated.

int n = stmt.executeUpdate (“update Emp_info set designation = ‘Analyst’ where emp no = 2371);

As mentioned earlier, executeUpdate method can also be used for DDL statements. For instance, the Emp_info table can be created as follows:

Stmt.executeUpdate (“create table Emp_info as (emp no varchar2 (10) primary key,” +”emp name varchar2 (10), designation varchar2 (10),” +”date_of_join date, salary float)”;

The return value of executeUpdate is zero when a DDL statement is passed as an argument to it.

Accessing rows returned from a query

Rows produced by an executeQuery () will be returned within an object of type ResultSet, which is of use in acting on it later. The following code shows the assignment of the result of the execution of the select statement to the instance rs of the ResultSet object.

Statement stmt =dbCon.createStatement ();

String sql = “select *from Emp_info”;

ResultSet rs = stmt.executeQuery (sql);

Note that the executeQuery method returns a ResultSet object that contains the results of

the query, whereas the executeUpdate method returns an int that represents the number of rows updated by the SQL statement.

Rows are retrieved from a ResultSet object by iterating through each of the rows and requesting information on the contents of each column. Iteration through its rows is similar to iterating through a set of elements in an Enumeration object.

The ResultSet class provides a cursor (also called handle) that can be used to access each row. The method next () of the ResultSet class is used to move the cursor that points to a row in the result set. Once the cursor is positioned on a row, we can request the data for each of its columns. Initially the cursor is set just before the first row. The first invocation of the method next sets the cursor on the first row. That is, to access the first row in the result set, the method next must be called once. Each invocation of next makes the cursor move to the next row. The method next returns a boolean value based on whether the next row is present. If a row exists, it returns true, otherwise, it returns false. Table gives a description of the methods in the ResultSet class.

Accessing column data

The method getXXX is used to access the columns in a row that are being pointed by the cursor currently. Here, XXX represents a Java data type. such as, for example, int As each column may contain a different data type, we need a ResultSet method specific to that data type. The method getInt (int column) can be used to retrieve a column with an integer value and getString (int column) can be used to retrieve a column with a string value. Under usual circumstances, we can use the getString(int column) method to get all types of database value. In such cases the retrieved values will be converted to a string type in Java.

                                             Table Methods in the ResultSet class.

Method

Description

public boolean absolute (int row) throws

SQLException;

This method moves the cursor to the row which has been specified by the parameter row.

public void afterLast () throws

SQLException;

This method moves the cursor to lie after the last row of ResultSet.

public boolean first () throws

SQLException;

This method moves the cursor to the first row of the ResultSet class.

public boolean last () throws

SQLException;

This method moves the cursor to the last row of ResultSet.

public int getRow () throws SQLException;

This method gets the current row number of the ResultSet object.

public boolean relative (int row)

SQLException;

This method moves the cursor by the specified number of rows relative the current row.

public boolean movePrevious ()

SQLException;

This method moves the cursor to the row preceding the current row.

public boolean rowUpdated () throws

SQLException;

This method answers whether the current row has been updated. The value returned by it depends on whether the result set can detect updates.

public boolean rowInserted () throws

SQLException;

This method answers whether the current row has had an insertion. The value returned by it depends on whether this ResultSet object can detect visible

Inserts.

public boolean rowDeleted () throws

SQLException;

This method answers whether a row has been deleted. A deleted row may leave a visible hole in a result set.

public void insertRow () throws

SQLException;

This method inserts the contents of the insert row into this ResultSet object and into the database.

public void updateRow () throws

SQLException;

This method updates the underlying database with the new contents of the current row of this ResultSet object.

public void delete () throws SQLException;

This method deletes the current row from this ResultSet object and from the underlying database.

A call to the next method sets the cursor to the next row whereas a call to getXXX method accesses a particular column in a row.

To retrieve a column value, the column name (or column number) is to be specified as a

parameter to the getXXX method. The use of the method getInt (2) is shown in the following example:

Statement stmt= con.createStatement ()

String sql=”select * from Emp_info”;

ResultSet rs=stmt.executeQuery ();

while (rs.next ())

{

     String name = rs.getString (1);

     int age = rs.getInt (2);

     System.out.println (name+” ” +age);

}

In the above example, the parameter 1 in the line rs.getString (1) indicates that it refers to the first column and rs.getInt(2) refers to the second column. Specifying columns is allowed by JDBC in the ResultSet and is done by using either the column name or the column number in the result set. For instance, since emp no is the first column in the Emp_info table, the results of using the following two statements are identical.

String name = rs.getString (“emp no”) and

String name = rs.getString (1).

Note that the column number (in the above statement, 1 is the column number) refers to the column number in the result set and not in the database table.

In some cases, data accessing methods will return null values, which looks ambiguous. The class ResultSet provides a method wasNull () that can be used after each column access. The method getObject () can be used to avoid the need for calls to wasNull (). The method getObject () returns the contents of the row according to the Java type which corresponds to its SQL type (the method uses metadata to determine this).

The programmer must know the format of the rows for the table or view they are working

with. This format of table can be known by accessing the metadata related to the database. A number of methods are provided by the JDBC to know the cursor position in the result set: these are getRow (), isFirst (), isBeforeFirst (), isLast () and isAfterLast ().

By default, JDBC allows the cursor only to scroll forward and the retrieved columns values are read-only. Further, JDBC 2.0 API (Java2 SDK, Standard Edition, version 1.2) provides a set of updater methods (to update the table) to the interface and has made it capable of being scrolled also (that is, it moves in any direction). Here is an example of how to create a result set

Statement stmt = dbCon.createStatement (ResultSet.TYPEFORWARD_ONLY,

ResultSet.CONCUR_READ_ONLY);

The other parameter options available are presented in Table

                        Table Parameter options for create statement.

Fetch direction

Updateable type

TYPE_FORWARD_ONLY

CONCUR_READ_ONLY

TYPE_SCROLL_INSENSITIVE

CONCUR_UPDATABLE

TYPE_SCROLL_SENSITIVE

 

In addition to the next () method, the scrollable cursors in JDBC 2.0 API provide options such as absolute, previous and relative. That is, in a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position or to a position relative to the current row. Examples of these are given below:

rs.absolute (5); // move the cursor to the fifth row of rs (absolute position from the first row)

rs.relative (5); // move forwards five rows from the current row

rs.relative (-2); // move backwards two rows from the current row

rs.previous () // move one row backwards from the current position.

With the help of JDBC 2.0 API, result sets can also be used to update a data source by

positioning on the row and specifying the replacement value then calling updateRow (). A similar set of methods can be used to insert rows.

The updater methods may be used in two ways: (i) to update a column value in the current row and (ii) insert a row with column values into a table.

The following code fragment updates the NAMEcolumn in the fifth row of the ResultSet

object rs and then uses the method updateRow to update the data source table from which rs was derived.

rs.absolute (5);

rs.updateString (“emp name”, “Kumar”);

rs.updateRow () ;

An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the cursor to the insert row, builds a two-column row and inserts it into rs and into the data source table using the method insertRow.

rs.moveToInsertRow ();

rs.updateString (1, “Kumar”);

rs.updateString (2, “2384”);

rs.insertRow ();

rs.moveToCurrentRow ();

The method Prepared Statement

 

In some cases, there will be a situation in which the SQL statement can be executed more than  once. So, to avoid constructing a new execution plan for each SQL statement we can use the PreparedStatement method. Using this, the execution plan needs to be prepared only once. That is, this statement allows the creation of a parameterized statement for which values can be inserted during the run-time, thereby allowing the same SQL statement to be used many times, each with different parameters.

Look at the following example of PreparedStatement:

String sql = “insert into Emp_info values (?,?,?,?,?)”;

PreparedStatement pstmt = dbCon.prepareStatement (sql);

boolean finished=false;

while (!finished)

{

      if (emp name.equals (“end”))

      finished = true;

      else

       {

            pstmt.setString (1, emp no);

            pstmt.setInt (2, emp name);

            pstmt.setString (3,designation );

            pstmt.setDate (4,date);

            pstmt.setFloat (5,salary);

            pstmt.executeUpdate ();

       }

}

pstmt.c1ose ();

The question marks in the above example indicate positions where parameter values are to be placed (these are also called place holders). The code pstmt.setString(1, emp no) sets the value of the first parameter to the string contained in the emp no variable. When accessing values returned from a query, the programmer needs to know the type of the database field the parameter corresponds to.

While using PreparedStatment, there is no need to pass an argument to the executeUpdate method as it already contains the SQL statement that is to be executed.

In the previous example, to repeat the execution of the prepared statement we used the variable finished. First, it is set to false, then the other variables employee number, name, designation, date of joining and salary_in_rupees are read and then the prepared statement is executed. When the name variable ‘end’ is read then the program comes out of the loop by resetting the value of the variable finished as true.

The c1earParametersO method (not shown in the above example) can be called to clear the values that are set using setXXX method.]

The method CallableStatement

The method CallableStatement is used to execute the stored procedure in order to access the database.

The stored procedure calculate_netsal () calculates the net salary based on gross salary stored in the salary field of the Emp_info table stored in SQL server database. The input to this procedure is employee number and the percentage of deductions. Let the stored procedure be the following set of statements:

CREATE PROC calculate_netsal @id varchar (10),

@percentage int ,

@net float OUTPUT

AS

declare @gross float

SELECT@gross= gross from Emp_info where emp no=@id>

SET @net=@gross-(((@gross)*(@percentage))/100)

RETURN (0)

The CallableStatement can be used for the above program as follows:

CallableStatement cstmt = dbCon.prepareCall (“{call calculate_netsal(?, ?, ?)}”);

cstmt.registerOutParameter (3, java.sql.FLOAT);

cstmt.setString (1, emp no);

csmt.setInt (2, percentage)

cstmt.execute ();

out.println (“Net salary: ” + cstmt.getFloat (3));

The method registerOutputParameter () registers the third parameter as an OUT parameter (or a call-by-reference parameter) of type float.

The three JDBC statement types, namely Statement, PreparedStatementand CallableStatement, are used to pass the SQL statements to the DBMS; however, all these three statements differ from each other in the timing of the SQL statement preparation and the statement execution. We first look into how an SQL statement in a programming language code is executed by a DBMS. A Java program first builds the SQL statement in a string buffer and hands over the same to the DBMS through API calls. The SQL statement need to be checked for correctness of syntax and then converted to an executable form.

The DBMS first parses the statement. If the statement is syntactically not correct, the DBMS returns an error condition to the driver, which generates an SQLException. Otherwise, the DBMS generates different query plans and selects an optimal plan based on the cost of execution. This optimal plan in turn gets converted into a binary execution plan. After the execution of the binary code, the DBMS returns an identifier to the application program.

Here is how each JOBC Statement is prepared and executed.

• The Statement object-the SQL statement is prepared and executed in one step in the Java code.

• The PreparedStatement object-The driver stores the execution plan handler for later use.

• The CalledStatement object-The SQL statement is actually making a call to a stored

procedure that is usually already optimized.

When using a simple Statement object, the optimal query plan is generated each time an SQL statement is executed. In the case of the PreparedStatment object, it is required to generate the  optimal query plan for an SQL statement once and it can be used several times. For instance, when inserting a number of rows in a table, we have to execute the same Statement object more than once (with a different set of row values). Thus, to execute an SQL statement several times, it takes less time if the PreparedStatement is used. In the case of the CalledStatement object, the binary code is executed which was previously optimized and stored in the database.

How to Working with JDBC

By Dinesh Thakur

Java database connectivity is essential for building stand-alone database applications and also for developing dynamic Java-based web applications. Before working with JDBC, it is required to install Java, a JDBC driver and the DBMS on the computer systems. Usually, the JDBC—ODBC bridge driver is bundled with the JDK.

Accessing a database using JDBC

The JDBC API provided by Sun Microsystems is designed to allow access to third-party database products. It causes the applications to be platform-independent and also allows making vendor-specific calls to take advantage of different features of database products. To be able to exploit this feature vendors must provide classes for using their database. The JDBC API also allows the programmer to access databases that reside on local as well as remote systems.

Registering the Driver

To start the process of accessing a database, first load the Driver class into the JVM for a specified JDBC driver, which allows the program to communicate with the database. Loading of JDBC Driver class registers itself with the DriverManager. The method Class.forName () is used for this purpose.

The following statements describe the way of loading drivers of the MS SQL server type

(type 4), Oracle thin driver type (type 4) and the IDBC-ODBC bridge driver type (type I),

respectively.

• Class.forName (“com.microsoft.jdbc.sqlserver.SQLServerDriver”);

• Class.forName (“oracle.jdbc.driver.OracleDriver”);

• Class.forName (“sun.jdbc.odbc.jdbcOdbcDriver”);

Before loading the Driver class, classpath is to be set equal to the driver classes. If this is not done, then the Class.forName () method throws the exception ClassNotFoundException.

Consider the example of setting the class path for an Oracle thin driver:

Set classpath=%classpath%;<location-of-oracle-driver>/classes12.jar ;

location-of-oracle-driver will specify the path of the Oracle driver class. This class had one static block. Once the class is loaded, this static block is executed for the purpose of registering the driver with the DriverManager class. This DriverManager class internally uses the Driver class.

Connecting to the Database

Once the driver is loaded, we can get the connection to the database using the static get connection () method of the DriverManager class.

Connection dbcon = DriverManager.getConnection (url, userid, password);

The getConnection () method has three parameters: url, userid and password. The parameters userid and password represent the user name and password that are used to access users’ database. DriverManager matches the parameter url with the registered driver classes and returns the Connection object related to that URL.This Connection object is used to create the JDBC statement that passes the SQL statement to the database management system.

The location of a database is specified using an URL of the following form:

<Protocol>:<subprotocol>:<subname>

Here, we are using the IDBC so protocol is normally jdbc. Subprotocol specifies the database we are using and the version of the database and subname is the name of the data source, which identifies the location of the database.

In the following example, the specification to be following when using the JDBC-ODBC bridge driver (that uses the ODBC) to access the database is given:

jdbc:odbc:dsn

Here, dsn is the data source name for any database (SQL server, Oracle, MS-access) system.

Note that subname can take a slightly different form if the database is on a remote system, it includes the machine, port number and database location on the remote system.

Connecting to a SQL server database with a type-four SQL driver

The statements to be used in this case are the following:

Class.forName (“com.microsoft.jdbc.sqlserver.SQLServerDriver”); //registering driver

String url = “jdbc:microsoft:sqlserver://”+host+”:1433″;

Connection dbcon = DriverManager.getConnection(url, userid, password);

Here, the host specifies the name of the system where the database server is located. The actual name of the host has to be substituted in place of the word host.

Connecting to Oracle server using Oracle thin driver

The statements to be used in this case are the following:

Class.forName (“oracle.jdbc.driver.OracieDriver”);

String url = “jdbc:oracle:thin:@” +host+”:1521 :”+dsource;

Connection dbcon= DriverManager.getConnection (url, userid, password);

The term dsource specifies the service name of the oracle.

Connecting to any database using the bridge driver

The statements used in this case are the following:

Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);

url = “jdbc:odbc:dsn”;

Connection dbcon=DriverManager.getConnection (url);

Here, dsn is the data source name of the database that we want to connect to. The actual name of the dsource and dsn have to be given here in a real program.

The object returned by getConnection () is a Connection object for the database. We use this connection object to submit any SQL queries or updates to the database.

Some of the methods in the DriverManager class are given in Table

Table Some important methods in the DriverManager class.

Method

Description

public static void deRegisterDriver (Driver driver) throws SQLException;  

This method unregisters or cancels the registration of the specified driver.

public static Connection getConnection (String url) throws SQLException;  

This method returns the Connection object by using the URL.

public static Connection getConnection (String url, Properties info) throws SQLException;

Properties naturally specifies user name and the password.

public static Connection getConnection (String url, String user, String pass) throws SQLException; 

The third form takes url and userid and password and returns the Connection object.

  

public static Driver getDriver (String url)

This method Returns the Driver object of the

specified URL.

public static Enumeration getDrivers () throws SQLException;  

This method Returns the all JDBC drivers currently loaded or registered with the DriverManager class.

public static void registerDriver (Driver driver) throws SQLException

This method registers the currently specified driver with the DriverManager. A newly loaded Driver implicitly calls this method.

 

Explain About JDBC Architecture

By Dinesh Thakur

Below Figure is a representative sketch of the JDBC architecture. This can be used in Java applications,applets, servlets or any other program where Java codes used. Java codes only interact with theJDBC Application-Program Interface (API). The JDBC API is a simple SQL-Level interface,which allows execution of SQL statements through Java.

The API consists of a set of interfaces and classes designed to perform actions on a database. The JDBC API class DriverManager, which is used to establish the connection to the database, is responsible for managing the different JDBC drivers. Other classes of JDBC API are useful when the programmer wishes to develop specific drivers of her own. The JDBC-ODBC bridge performs translations of JDBC calls to an ODBC-compatible format. This bridge is required to maintain compatibility with non-JDBC databases.

                         The JDBC architecture

Interfaces in JDBC API

The JDBC API is defined in java.sql package and it consists of the following interfaces:

• The interface java.sqI.Environment, which allows the creation of new database connections.

• java.sql.Connection, which permits connecting to the database.

• java.sql.Statement, which is the container class for embedded SQL statements.

• java.sql.ResultSet, which allows accessing the results of a statement.

The different classes found in the JDBC API are listed below:

• Driver                           • SqlException                 • Date

• Driver Manager          • SqlWarning                    • Time

• DriverPropertyInfo    • ResultSet                        • Timestamp

• Connection                   • ResultSetMetaData     • Types

• Statement                     • DatabaseMetaData     • DataTruncation

• PreparedStatement

• CallableSatement

The implementation classes for the interfaces shown in italic, in the above list, are

database- vendor-specific.

Types of database driver

Database vendors can provide drivers of various types. Sun Microsystems have specified four types of driver:

Type l-Bridge Drivers These drivers use bridge technology like ODBC to connect to the database. The JDBC-ODBC Bridge Driver is the most commonly used driver.

Type 2-Part-Java Drivers This type wraps a thin layer of Java code over the native code libraries to implement JDBC.

Type 3-Network All-Java Drivers This type consists of a Java code which connects to middleware to access a database via a network protocol. Generally this type of driver is not used for data access.

Type4-Direct All-Java Drivers This type provides a pure Java JDBC implementation, which can be accessed directly and provides services to networking middleware. This is used mainly for internet applications.

WHAT IS JDBC?

By Dinesh Thakur

JDBC defines an API designed to support basic SQL functionality independent of any specific SQL implementation. This means the focus is on executing SQL statements and retrieving their results.

JDBC is an international standard for programming access to SQL databases. It was developed by JavaSoft, a subsidiary of Sun Microsystems.

      Relational Database Management System supports SQL. As we know that Java is platform independent, JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.

       Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not dependent upon any language.

       In short, JDBC helps the programmers to write Java applications that manage these three programming activities:

• Establishing a connection with a database or other tabular data source

• Sending SQL commands to the database

• Processing the results

Java Database Connectivity or in short JDBC is a technology that enables the Java program to manipulate data stored in a database. JDBC is a Java programming interface that allows the Java program to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystem.

     JDBC is similar to Micro ODBC interface to SQL database which is used for accessing and managing database. However, the difference is that while JDBC is specifically for Java program, ODBC is not dependent upon any language.

In short, JDBC helps the programmer to write Java applications that manage three programming activities.

1. It helps us to connect to data source like database.

2. It helps us to send queries and update statements to the database.

3. It helps us to restore and process the results it receives from the database in terms of answering your queries.

JDBC Versions

i. JDBC 1.0 API

ii. JDBC 1.2 API

iii. JDBC 2.0 optional package API

iv. JDBC 2.1 core API

v. JDBC 3.0 API

vi. JDBC4.0 API

Feature of JDBC 1.0 API

The JDBC 1.0 API was the first officially JDBC launched. It consisted of the following

Java classes:

Features of JDBC 1.2 API

i. It supports updatable ResultSets.

ii. New pass through scheduler for increased performance.

Features of JDBC 2.1 CORE API

i. Scrolls forward and backward Results or has ability to move to a specific row.

ii. We can use multiple SQL statements in database as a unit or batch.

Features of JDBC 3.0 API

i. A new concept has been added to API, that of SavePoint.

ii. DatabaseMetaData API has been added.

iii. Connection pool.

Features of JDBC 4.0

i. Auto-loading of JDBC driver class.

ii. SQL XML support.

JDBC Driver Model

JDBC supports two-tier and three-tier model:

I. Two-tier Model

In this model the Java applets and application are directly connected with any type of database. The client directly communicates with database server through JDBC driver.

                    Two-tier Model

As another layer, the Manager should communicate with various third party drivers that actually connect to the database and return information from the query or perform action specified by the query.

II. Three-tier Model

In this model, client connects with database server through a middle-tier server, which is used for various purposes. Middle-tier server performs various functions.

                  Three-tier Model

It extracts the SQL command from the client and sends these commands to the database server. Also, it extracts the result from the database server and submits the same to the client.

Exploring JDBC Architecture

JDBC is open specification given by Sun Microsystems having rules and guidelines to develop JDBC driver. JDBC driver is a bridge software between Java application and database software. It converts Java call to database call and vice versa. Java application talks with database server using JDBC driver.

              Exploring JDBC Architecture

• JDBC call converts database call.

• JDBC driver connects to database server and sends command to the database server.

• Database executes the statement.

• Sends the output back to JDBC driver.

• JDBC driver sends back to java application.

 Each JDBC driver is specific to one database software.

We can get the JDBC driver from three parties:

1. Sun Microsystems

2. Database vendor

3. Third party vendor

It is recommended to use database vendor- supplied JDBC drivers.

Non-Java applications use ODBC drivers to interact with database software.

     There are four different methodologies or mechanisms to develop JDBC drivers based on the rules and guidelines of JDBC specification. These are:

i.   Type-1(JDBC-ODBC Bridge Driver)

ii. Type-n Native API/ partly Java Driver)

iii. Type-3(Net-Protocol/All Java Driver)

iv. Type-4(Native- Protocol/All Java Driver)

 

i. Type-l(JDBC-ODBC Bridge Driver)

The type-1 mechanism-based drivers are given drivers to take the support of ODBC drivers while introducing to database software. In this process, the type 1 driver takes support of the native code to communicate with ODBC drivers.

                 Type-l (JDBC-ODBC Bridge Driver)

JDBC Type-1 driver is not specific to any database software because it does not interact with database software directly. It interacts with database software by using the database software-specific ODBC driver.

      Type-1 driver is supplied only by Sun Microsystems. It has a built-in JDK software. JDK software supplies a basic and built-in service called DriverManager which serves to manage a set of JDBC drivers and to establish the connection with database software by using JDBC driver.

Type-1 driver class name is: sun.jdbc.odbc.JdbcOdbcDriver

      Every JDBC driver must be registered with DriverManager service, as this creates JDBC class object in DriverManager service.

Advantages of JDBC-ODBC Bridge Driver

• Serves as a single driver that can be used to interact with different data stores.

• Allows you to communicate with all the databases supported by the ODBC driver.

• Represents a vendor-independent driver and is available with JDK

Disadvantages of JDBC-ODBC Bridge Driver

• Decreases the execution speed due to more number of transactions. (Include JDBC ODBC DB Native call)

• Depends on the ODBC driver due to which Java application indirectly becomes dependent on ODBC drivers.

ii. Type-2(JAVA to Native API)

Type-2 driver converts JDBC calls in a client machine. It uses native code to communicate with vendor database library. These native codes are usually written in C or C++.

                       Type-2 (JAVA to Native API)

Type-2 JDBC driver takes the support of vendor database software. In the figure, the java application is programmed using JDBC API, making JDBC calls. These JDBC calls are then converted into database specific native calls and the request is then dispatched to the database specific native libraries.

      Type-2 drivers are suitable to use with server-side application. It is not recommended to use type-2 drivers with client-side application since native libraries for the client platform should be installed on the client machines.

Advantages of Type-2 driver

• No need of working with ODBC

• Serves as the fastest driver compared to other types of drivers_

• Allows you to use the additional features provided by the specific database vendors to access the database which are even supported by JDBC specification.

Session Management

By Dinesh Thakur

In a web server, a session is a collection of all the requests made by a client (browser). HTTP is a stateless protocol. Between requests, it does not maintain any state of the client (browser). Suppose the client makes request for a web page, it should be checked whether the request is from an authorized user. It is impossible to check the authorization for each web page. It is necessary to maintain some information of the user while a user navigates between web pages. Thus, it is useful to maintain the state of client. The following processes arc used to maintain the state of a client:

• URL rewriting

• Hidden fields

• Cookies

• Sessions

Hidden fields Hidden fields are the easiest way of maintaining the state of a client. These are the same as the HTML input tags. These are specified as follows:

<inputtype=“HIDDEN” name=“item” value=“Book” >

These tags will not display anything on the web page but are very useful to present some information to the next page as name-value pairs.

Rewriting URLs Rewriting the URL plays an important role in the session management of the HTTP. This method passes the state information between the client and server by embedding the information as name-value pairs in the URL.

  <A href =“SampleServletlitem = Book&quantity =5“>ltems</A> or                

   <form method =“Get” action=“SampleServlet?item = Book&quantity=5“>

Name-value pairs are placed within the anchor tag separated by the ampersand (&). The Servlet API is capable of accessing the QueryString (name-value pairs after the URL that are found after the question mark (?)) by using the getParameterValue() and getParameterNames() methods of the ServletRequest object.

Cookies Another way to maintain the state of a client is by using cookies. A cookie is an object sent by the server to a client. A cookie is created by the server and sent to the client along with the requested response. Each cookie has a definite lifetime. In general, cookies are insecure and, thus, they are considered to make privacy issues difficult.

Cookies contain small bits of information created by the server and stored at the client machine. These are created when the client makes the first request to the servlet. They are sent to the client along with the response and stored in the client. With each subsequent request, the client sends the information contained in these cookies to the server as the request header.

The Servlet API provides the Cookie class to tackle the concept of cookies. This class manipulates all the technologies of the cookie. The constructor of the Cookie class is the following:

         public Cookie(String name ,String value);                    

After the Cookie class is created, some value is stored within this and it is added to the HttpServletReponse object using the addCookie method, as shown below:

         addCookie(cookie);

It is important that the cookie must be added to the response before any other response is created, including the content type.

Http sessions The state of the HTTP can also be maintained by using sessions. Like cookies, sessions are also used to store information except that the information is stored in the server machine under an unique session identification number. These session identification numbers also exist at the client as cookies. When a request is made, then the session identification number is also sent along with the request information so that the server can uniquely identify the client and provide the client information. The Servlet API provides the interface Httpsession which maintains the relevant information such as the unique session identification number and client specific information. The syntax for using HttpSession is as follows:

                      HttpSession session= httpservletrequest.getSession( )

Here httpservletrequest is an object of the HttpServletRequest interface.

Program Using HttpSession to maintain information on the client’s state.

import javax.servlet.*; 
import javax.servlet.http.*;
import java.io.*;
public class TestServlet extends HttpServlet
{
    String Name;
    public void init(ServletConfig config) throws ServletException
   {
        super.init(config);
        Name=config.getlnitParameter("name");
    }
  public void doGet(HttpServletRequest req,HttpServletResponse res) throws                  ServletException, IOException
    {
        res.setContent Type("text/html");
        PrintWriter pout=res.getWriter();
         // getting the session object
        HttpSession session=req.getSession();
        pout.write("Getting the Session id of servlet;"+ session.getld());
        pout.write("Here we are setting the session interval");
        session. set MaxInactivelnterval(20);
         // lnactive Interval is set
        pout.write("The Inactive interval:"+ session.getMaxlnactivelnterval());
        session.putValue("name", "Kumar");
        pout.write("Getting the session value:"+ session.getValue("name"));
        session.invalidate();
       pout.close();
    }
       public void destroy(){}
}
                      

Additional Capabilities of HTTP Servlets

By Dinesh Thakur

Of these, HTTP servlets have some additional objects that provide session-tracking capabilities, the servlet writer can use the HttpSession interface to maintain the state of a client between client requests upto some time period. The capability of maintaining cookies is also provided by the HTTP servlets, The servlet writer uses the Cookie class to save small bits of information within the client machine, which can be retrieved at request processing time, Program illustrates the use of the HttpServlets.

public class Servlet_A extends HttpServlet

{

                  public void doGet (HttpServletRequest request, HttpServletResponse response)

                  throws ServletException, IOException

               {

                          PrintWriter pout;

                        String title = “Http Servlet Example”;

                     // set content type and other response header fields first

                        response,setContent Type(“text/html”);

                       // then write the data of the response

                       pout = response,getWriter();

                       pout,println (“<html ><head><title> “);

                       pout,println(title);

                       pout,printl n(“</title></head><body>”);

                       pout,println(“<h1 >” + title + “</h1 >”);

                       pout,println(“<P>This is output from Servlet_A”);

                       for(int i=0;i<=5;1++)

                              pout,print(i+” “);

                              pout.println (“</body></html>”);

                              pout.c1ose();

                }

}

Servlet_A extends the HttpServlet class which, in turn, implements the Servlet interface. Here the title of the tag is displayed as the name of the browser window. Servlet_A overrides the doGet method in the HttpServlet class. The doGet method is called when a client makes a GET request (which is the default HTTP request method), and this results in the simple HTML page being returned to the client.

If a request is made to HttpServlet then the container delegates the request to the public service method within the servlet. This method will cast the ServletRequest, ServletResponse object to their corresponding HttpServletRequest and HttpServletResponse. Then this method will delegate the call to the protected service method. In the protected service method we call the method getMethod() on the request object, which will return the string specifying the type request. If the request is get then the doGet() method is called. In case the request is post then the doPost() method is called.

Objects of the HttpServletRequest class

Within the doGet method, the user’s request is represented by an HttpServletRequest object. An HttpServletResponse object represents the response to the user. Because text data is returned to the client, the reply is sent using the Writer object obtained from the HttpServletResponse object.

Objects of the HttpServlet Response class

An object of the class HttpServletResponse provides two ways of returning data to the user:

• The getWriter() method which returns a PrintWriter object.

• The getOutputStream() method which returns a ServletOutputStream object.

One way of handling this is to use the getWriter method to return text data to the user and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after the response is sent allows the server to know when the response is complete. The HTTP header data must be setbeforeaccessing the Writer or OutputStream. The HttpServletResponse class provides methods to set the header data. For example, the setContent Type() method is used to set the content type (This is the header used most by the developer). So, in general, it is preferable to set the content type before accessing the Writer object.

Examples of GET and POST Requests

To handle HTTP requests in a servlet, extend the Http5ervlet class and override the servlet methods that handle the HTTP requests made by the clients. Programs illustrate how to handle GET and POST requests. The methods that handle these requests are doGet and do Post.

HandlingGETrequestsHandling GET requests involves overriding the doGet method. Program illustrates the use of the GET request. The Get method, in general, sends requests to the servlet without passing any parameters. It is also possible to pass the parameter to the get method.

Program Using theGETrequest. 
import javax.servlet.*;
import javax.servlet.http*;
import java.util.*;
import java.io.*;
public class ServlecGet extends HttpServlet
{
             public void init(ServletConfig config) throws ServletException
            {
                    super.init(config);
             }
             public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException
            {
                    response.setContent Type("text/html");
                    PrintWriter pout = response.getWriter();
                    pout.println("<html><head><title> Receipt </title>" );
                    String date = new Date().toString();
                    pout.println("<h3> To day's date is:"+date);
                    pout.println ("</h3></head></html>");
                    pout.close();
            }
            public void destroy( )
           {
                    // destroyall resource if any connected to the servlet
           }
}

The Servlet_Get class extends the HttpServlet class and overrides the doGet method. To respond to the client, the doGet method in Programuses a Writer from the HttpServletResponse object to return text data to the client. Before accessing the writer, the content-type header is set in this program. At the end of the doGet method, after the response has been sent, the Writer is closed.

Handling POSTrequestsHandling POST requests involves overriding the doPost method. Programillustrates the means of overriding the doPost method. The Post method is used when information is passed to the servlet. If the doPost() method is overridden then the information has to be passed to the servlet.

Program UsingPOSTrequests

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class Servlet_Post extends HttpServlet
{
            public void init(ServletConfig config) throws ServletException
           {
                    super.init( config);
            }
            public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException. IOException
           {
                           response.setContent Type("text/html");
                           PrintWriter pout = response.getWriter();
                           pout.println("<html><head><title> Receipt </title>" );
                           String date = new Date().toString();
                           pout.println("<h3>" +date);
                           pout.println ("</h3></head></html>");
                           pout.c1ose();
            }
                      public void destroy( )
                 {
                                 // destroy allresource if any connected to the servlet
                  }
  }

Multi-tier Applications using JDBC from a Servlet

By Dinesh Thakur

Servlets are the server-side components that enhance the capability of Java-enabled servers and allow a variety of network-based services. For example, servlets with the database communication can facilitate solutions for distributed applications.

Typical three-tier architecture for database applications is shown in the Figure. The first tier (client) contains a browser (such as Netscape or Microsoft IE). The second tier contains the Java-enabled web server and the JDBC driver (for example, JDBC-ODBC bridge driver). The database is contained in the third tier. Servlets allow dynamic HTML pages to communicate with the client and database through JDBC.

                Three-tier architecture

Writing JDBC/Servlet

Consider the example of the TestDataBaseCon servlet in Program which illustrates the use of the servlet framework in JDBC/Servlet communication. This servlet makes a connection to the database and returns data in HTML form.

Program Making a database connection using the init() method.

public class TestDataBaseCon extends HttpServlet
{
       Connection connection = null;
       public void init() throws ServletException
      {
              try
              {
                      String host = config.getlnitParameter("host");
                      String uname = config.getlnitParameter("user");
                      String pwd = config.getlnitParameter("Password");
                      Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                      url = "jdbc:microsoft:SqIServer://"+host+":1433;"+
                        "User = "+uname+ "Password="+pwd;
                      con= DriverManager.getConnection(url);
               }
                      catch(ClassNotFoundException e)
                           {
                                 System.out.println("problem in loading the class:");
                           }
                      catch(SQLException e)
                          {
                                   System.out.println("Sql error");
                           }
       }
}

Servlets are built by extending a basic Servlet class and overriding some of the methods to deal with incoming client requests. TestDataBaseCon extends the HttpServlet class that provides most of the capabilities needed to serve client requests. After the servlet is loaded, three main methods are involved in the life-cycle of a servlet.

Initialization

On receiving the request from the client, the servlet engine (container) checks whether it is the first request to the servlet. If it is the first request, then the servlet engine instantiates the servlet and initializes it by sending the initialization method call that is, init(). The code related to database connections is placed in the init() method.

Service calls

After initialization, servlets are capable of handling many requests, by means of a single servlet instance. Each client request generates one service call (that is, thread to provide service) and these calls can be concurrent. In a JDBC servlet, the service calls process incoming name value pair information from a browser, and return raw data or HTML pages (dynamic or static) as output. Note that in the name-value pair, the name indicates the parameter name and value indicates the value(s) of that parameter.

Servlet termination

The destroy method provided by the HttpServlet class destroys the servlet and logs the destruction. This method is overridden to destroy the resources used in the servlet. The destroy method should undo any initialization work that is done in the init() method. In the TestDataBaseCon example of Program, the destroy method is the used for this purpose.

Program Using the destroy method for servlet termination.
public class TestDataBaseCon extends
{
        Connection connection =  null;
          // init() method
         // service() method
       public void destroy()
       {
                   // Close the connection and allow it to be garbage collected
                   connection.close();
                connection =  null;
       }
}

A server calls the destroy method after all service calls have been completed, or a server specific number of seconds have passed without there being any request from the client. If the servlet handles any long-running operations, the service methods might still be running when the server calls the destroy method. Hence, it must be ensured that those threads complete their function. The destroy method described in Program expects all client interactions to be completed when it is called, because the servlet has no long-running operations.

A sample JDBC/Servlet application

Program gives a simple JDBC/Servlet application . 
Program Illustration of initializing, implementing and destroying a servlet.
public class TestDataBaseCon extends HttpServlet
{
  //declaration of the connection
  private Connection con;
  public void init(ServletConfig conf) throws ServletException
  {
           // initializing the servlet
          super.init( conf);
           try
          {
               String host = config.getlnitParameter("host");
               String dsource = config.getlnitParameter("dsource");
               String uname = config.getlnitParameter("uname");
               String pwd = config.getlnitParameter("pwd");
                // loading the driver class and registering to DriverManager
               Class.forName(" oracle.jdbc.driver.OracleDriver");
                 //getting connection
               ur1="jdbc:oracle:thin:@"+host+":1521:"+dsource;
               con =DriverManager.getConnection( url,uname,pwd);
          }
                catch (ClassNotFoundExcepticn e)
               {
                       System.out.pritnln ("Driver class is not found:" + e.getMessage());
                }
                catch (SQLException se)
                {
                       System.err.println("Problem in making the connection:" + se);
                 }
    }
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
               res.setContent Type("text/html");
    try
  {
            PrintWriter pout = res.getWriter();
            pout.println("<html>");
            pout.println("<head>");
            pout.println("<title>Sample JDBC Servlet Demo</title>");
            pout.println ("<lhead>");
            pout.println("<body >");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from Emp_info");
             pout.println("Getting the values from the Oracle Table")
             while(rs.next())
             {
                         pout.println(rs.getString(1)+" ");
                         pout.println (rs.getString(2));
               }
                          pout.println();
                          rs.c1ose();
                          stmt.c1ose();
   }
             catch(SQLException e)
          {
                        // SqlException describes problem with connection
                         pout.println("An SQL Exception was thrown.");
         }
             catch(IOException e)
            {
                        pout.println("An IOException was thrown.");
              }
             pout.println("</body>");
             pout.println ("</html>");
   }
             //closing the connection to the database
             public void destroy()
            {
                   con.c1ose();
            }
}

MySql DayOfMonth() in Java Servlet

By Dinesh Thakur

This function will return the Value of Month’s Day in Numeric value (1 to 31).

First i create a database named ‘dbase’ within the reference of mySql(php myAdmin).then according to program need i import all the required java packages from java library. Then i create a class named ‘MySqlDayOfMonth’ which extends the ‘HttpServlet’. Then i use service()Method that will use to getting request from the doGet()Method for output generating. Then i loaded all the required drivers for the database accessing. After that i declare variables like ‘connection’ this variable is responsible for the creating a link between database and the java code. The other i declare the ‘resultSet’ this variable is use to get value from the columns and rows. In other variable i use ‘preparedStatement’ this will use to execute the selected query like executeQuery() as (Select DAYOFMONTH(‘2014-05-31’)). Here in the last i use doGet()Method for output on the web browser.

Here in the last i use ‘HTML’ Code and tags that will present the output in tabular form on the web browser.

EXAMPLE 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDayOfMonth extends HttpServlet
 {
      public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
             {
                  Class.forName(driver);
                  con = DriverManager.getConnection(url,uid,psw);
                  ps=con.prepareStatement("Select DAYOFMONTH('2014-05-31') AS dm");
                  rs = ps.executeQuery();
               String title = "Using Day Of Month Function";
                 String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                 "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Day</th>\n"+ "</body> </html>");
                 while(rs.next())
                       {
                           String curr = rs.getString(1);
                        disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                       }     
             }        
                        catch(Exception e) 
                         {
                            e.printStackTrace();
                         }
                            disp.close();
      }
                              public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                 {
                                     doGet(rq,rp);
                                 }
}
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDayOfMonth</servlet-name>
   <servlet-class>MySqlDayOfMonth</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDayOfMonth</servlet-name>
   <url-pattern>/MySqlDayOfMonth</url-pattern>
</servlet-mapping>

MYSQL DAYNAME() in Java servlet

By Dinesh Thakur

The Function ‘DAY NAME’ will show the day’s Name of the Month.

First we need a table that I create in the database named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the java packages from java library. Then i made a class which extends the ‘HttpServlet’ Completely. Here after i use service()Method which will use to getting request from the doGet()Method for output on the web browser. Before declaring the required variable i loaded all the drivers for database accessing. Then i declare variables like first i declare ‘connection’ this variable will use to create a link between database and the java code. The other i declare ‘resultSet’ this variable will use to fetch the desired values from the selected columns and the rows from table. The last variable will be ‘preparedStatement’ that variable will be use to execute the selected query like executeQuery() as (Select DAYNAME(‘2014-05-31’)). Here i also use doGet()Method in the last step which will use to bring output on the web browser.

to getting output on the web browser i used ‘HTML’ code and tags that will bring output in tabular form that will make it a manner form.

  
EXAMLPE
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDayName extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
      {
         rp.setContentType("text/html");
         PrintWriter disp = rp.getWriter();
         String driver = "com.mysql.jdbc.Driver";
         String url = "jdbc:mysql://localhost/dbase";
         String uid = "root";
         String psw = "root";
         Connection con=null;
         PreparedStatement ps = null;
         ResultSet rs;
         try
           {
               Class.forName(driver);
               con = DriverManager.getConnection(url,uid,psw);
               ps=con.prepareStatement("Select DAYNAME('2014-05-31') AS dn");
               rs = ps.executeQuery();
            String title = "Using Day Name Function";
              String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
            disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Day</th>\n"+ "</body> </html>");
              while(rs.next())
                  {
                       String curr = rs.getString(1);
                    disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                  }     
          }           
                    catch(Exception e) 
                      {
                        e.printStackTrace();
                       }
                        disp.close();
      }
                          public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDayName</servlet-name>
   <servlet-class>MySqlDayName</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDayName</servlet-name>
   <url-pattern>/MySqlDayName</url-pattern>
</servlet-mapping>

MySql DateSub() in Java Servlet

By Dinesh Thakur

The Function ‘DATE_SUB’ will subtract the date with required Interval.

Here in first instance i made a table in database named ‘dbase’ within the reference of mySql (php myAdmin). I import all the required java packages from java library. I use to make a class named ‘MySqlDateSub’ which extends the ‘HttpServlet’. I use here service()Method which will use to get request from the doGet()Method. Then i loaded all the required drivers for database accessing. Then after i declare the variables like first i declare ‘connection’ this variable will be responsible for the creating link between the database and the java code. The other variable will be ‘resultSet’ this will does the job to fetching value from the desired column and rows as required. Then other one I declare ‘preparedStatement’ that will be responsible for executing the selected query like executeQuery() as (Select DATE_SUB(NOW(),INTERVAL 1 DAY)). After declaring all the variables i use doGet()Method which will use to get output on the web Browser.

I Use ‘HTML’ code and some tags which will show the output in tabular form on the web browser. 

EXAMLPE 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDateSub extends HttpServlet
 {
      public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
             {
                 Class.forName(driver);
                 con = DriverManager.getConnection(url,uid,psw);
                 ps=con.prepareStatement("Select DATE_SUB(NOW(),INTERVAL 1 DAY)");
                 rs = ps.executeQuery();
              String title = "Date Subtraction";
                String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Date & Time After Subtraction </th>\n"+ "</body> </html>");
                while(rs.next())
                  {
                       String curr = rs.getString(1);
                     disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                  }     
            }         
                     catch(Exception e) 
                       {
                        e.printStackTrace();
                       }
                        disp.close();
        }
                         public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDateSub</servlet-name>
   <servlet-class>MySqlDateSub</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDateSub</servlet-name>
   <url-pattern>/MySqlDateSub</url-pattern>
</servlet-mapping>

MySql Date Function in Java Servlet

By Dinesh Thakur

The function ‘DATE’ will show the present date of system.

i make a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin). Then i import all the required java packages from java library. Then i made class which extends ‘HttpServlet’ named ‘MySqlDateFunction’.i use here serviceMethod() that will use to getting the request from the doGet()method. Before declaring desired variables i loaded all the required drivers for database accessing. Then after i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also which is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (SELECT now(), date(now())).i use doGet()Method that will get Output on the web browser.

While getting the output on the web browser i use ‘HTML’ code and tags.

 EXAMLPE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDateFunction extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
             {
                 Class.forName(driver);
                 con = DriverManager.getConnection(url,uid,psw);
                 ps=con.prepareStatement("SELECT now(), date(now()) as dt");
                 rs = ps.executeQuery();
               String title = "Date Function";
                 String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                 "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Current Date & Time</th><th>Desired Date</th>\n"+ "</body> </html>");
                while(rs.next())
                   {
                       String curr = rs.getString(1);
                     String date=rs.getString(2);
                     disp.println("<tr><td align=\"center\">" + curr +"<td align=\"center\">" + date +"</td></tr>" );  
                  }     
             }        
                    catch(Exception e) 
                       {
                         e.printStackTrace();
                       }
                         disp.close();
     }
                           public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDateFunction</servlet-name>
   <servlet-class>MySqlDateFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDateFunction</servlet-name>
   <url-pattern>/MySqlDateFunction</url-pattern>
</servlet-mapping>

MySql DateFormat() in Java Servlet

By Dinesh Thakur

The Function ‘DATE_FORMAT’ will use to see the format of the date.

First i make a table in database named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the required java packages from the java library. Then i made a class named ‘MySqlDateFormat’ which extends ‘HttpServlet’. Then after i use service()Mehod which will get the request from the doGet()Method. Then i loaded all the require drivers for the database accessing. Here i declare the variables like ‘connection’ this variable will take over to create a link between a database and the java code. The other i declare ‘resultSet’ this will use to fetch the value from the columns and the rows from selected table. Then i declare the ‘preparedStatement’ this variable will execute the selected query like executeQuery() as (Select DATE_FORMAT(NOW(),’%W, %M %e, %Y’)). I here use doGet()Method that will bring the output on the web browser.

On the web Browser i use ‘HTML’ tags that will represent the output in tabular form.

EXAMLPE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDateFormat extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
           rp.setContentType("text/html");
           PrintWriter disp = rp.getWriter();
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/dbase";
           String uid = "root";
           String psw = "root";
           Connection con=null;
           PreparedStatement ps = null;
           ResultSet rs;
           try
            {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("Select DATE_FORMAT(NOW(),'%W, %M %e, %Y')");
                rs = ps.executeQuery();
             String title = "Date Format";
               String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Date Formating </th>\n"+ "</body> </html>");
                while(rs.next())
                  {
                      String curr = rs.getString(1);
                   disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                  }     
            }         
                   catch(Exception e) 
                       {
                         e.printStackTrace();
                       }
                         disp.close();
         }
                           public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                              {
                               doGet(rq,rp);
                              }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDateFormat</servlet-name>
   <servlet-class>MySqlDateFormat</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDateFormat</servlet-name>
   <url-pattern>/MySqlDateFormat</url-pattern>
</servlet-mapping>

MySql DateDiff() in Java Servlet Example

By Dinesh Thakur

This Function ‘Date_Diff’ will subtract the Two Dates.

first i make a table in database named ‘dbase’ within the reference of mySql(php myAdmin).then i import all the required java package from java library. I make a class named ‘MySqlDateDifference’ extends the ‘HttpServlet’. I use here serviceMethod() which is use to getting request from the doGet()Method for output. Before activating all the variable i loaded all the required drivers for the database accessing then after i declare variables like first i declare ‘connection'(this variable will act as to create a link between database and the actual code. Here i declare second one is ‘resultSet’ this will take the responsible for fetching the value from columns and the selected rows. Here i declare one more ‘preparedStatement’ this will use to executing the selected query like executeQuery() as (Select DATEDIFF(‘2014-05-30′,’2014-05-29’)). I use doGet()Method which will bring the output on the web browser.

i use ‘HTML’ code and tags for getting output in tabular form that make output in the manner way.

 

EXAMPLE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlDateDifference extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
      {
          rp.setContentType("text/html");
          PrintWriter disp = rp.getWriter();
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost/dbase";
          String uid = "root";
          String psw = "root";
          Connection con=null;
          PreparedStatement ps = null;
          ResultSet rs;
          try
           {
              Class.forName(driver);
              con = DriverManager.getConnection(url,uid,psw);
              ps=con.prepareStatement("Select DATEDIFF('2014-05-30','2014-05-29') AS dfd");
              rs = ps.executeQuery();
              String title = "Date Difference Beetween Two Dates";
              String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
            disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
              "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Date Difference </th>\n"+ "</body> </html>");
              while(rs.next())
                  {
                      String curr = rs.getString(1);
                   disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                  }     
           }          
                   catch(Exception e) 
                         {
                                e.printStackTrace();
                         }
                                disp.close();
        }
                                  public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                                    {
                                     doGet(rq,rp);
                                    }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlDateDifference</servlet-name>
   <servlet-class>MySqlDateDifference</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlDateDifference</servlet-name>
   <url-pattern>/MySqlDateDifference</url-pattern>
</servlet-mapping>

MySql CurrTimeStamp() in Java Servlet

By Dinesh Thakur

This Function ‘TIME_STAMP’ will return the date or date time expression.

First i make a table in database named ‘dbase’ within the reference of mySql(php myAdmin).then i import all the mandatory java packages from the java library as required for program. I made a class named ‘MySqlCurrTimeStamp’ which extends ‘HttpServlet’.i use serviceMethod() which is been carry the request from doGet()Method for Output. Then after to declare the variable i loaded all the required drivers before for database accessing. Here i declare the variables like ‘connection’ this variable will create a link between database and java code. Then i call ‘resultSet’ this will be responsible for Getting value from the selected columns and the rows.

Then i declare ‘preparedStatement’ which will get to execute the selected query like executeQuery() as (Select CURRENT_TIMESTAMP() AS now). Here i use doGet()Method which will use to get output on the web browser.

While on the web browser to get output in tabular form i use ‘HTML’ code and tags for a manner way look. 

  
EXAMPLE
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCurrTimeStamp extends HttpServlet
 {
     public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
      {
        rp.setContentType("text/html");
        PrintWriter disp = rp.getWriter();
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost/dbase";
        String uid = "root";
        String psw = "root";
        Connection con=null;
        PreparedStatement ps = null;
        ResultSet rs;
        try
         {
            Class.forName(driver);
            con = DriverManager.getConnection(url,uid,psw);
            ps=con.prepareStatement("Select CURRENT_TIMESTAMP() AS now");
            rs = ps.executeQuery();
            String title = "Using Current Time Stamp Function";
            String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
            disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
            "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Time Stamp Example  </th>\n"+ "</body> </html>");
            while(rs.next())
               {
                  String curr = rs.getString(1);
                disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
               }     
         }
                catch(Exception e) 
                  {
                       e.printStackTrace();
                  }
                       disp.close();
      }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlCurrTimeStamp</servlet-name>
   <servlet-class>MySqlCurrTimeStamp</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCurrTimeStamp</servlet-name>
   <url-pattern>/MySqlCurrTimeStamp</url-pattern>
</servlet-mapping>

MySql CurrTime() in Servlet Example

By Dinesh Thakur

This Function will represent the current Time on the web browser.

first i make a table in database named ‘dbase’ with required fields and values which is under the reference of mySql(php myAdmin). Here i import all mandatory java package from the java library as program needs. Then after i make a class named ‘MySqlCurrTime’ extends ‘HttpServlet’. And here i use serviceMethod() which will get request from the doGet()Method for getting output on the web browser. After i load all the required drivers for accessing database. After then i declare mandatory variables like i declare ‘Connection’ this variable does the job to create a link between database and the actual code. The other one i declare is ‘resultSet’ that will fetch the value from selected column and rows. Now here i declare the ‘preparedStatement’ that will use to execute the selected query like executeQuery() as (“Select CURTIME() AS now”). Here i use the doGet()Method for output on a web browser.

For getting the output in the tabular form i use ‘HTML’ code and tags that will show output in a manner way on web browser. 

 EXAMLPE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCurrTime extends HttpServlet
 {
      public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
       {
          rp.setContentType("text/html");
          PrintWriter disp = rp.getWriter();
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost/dbase";
          String uid = "root";
          String psw = "root";
          Connection con=null;
          PreparedStatement ps = null;
          ResultSet rs;
          try
           {
                Class.forName(driver);
                con = DriverManager.getConnection(url,uid,psw);
                ps=con.prepareStatement("Select CURTIME() AS now");
                rs = ps.executeQuery();
                String title = "Using Current Time Function";
                String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
               "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Current Time  </th>\n"+ "</body> </html>");
               while(rs.next())
                 {
                    String curr = rs.getString(1);
                 disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
                 }     
           }          
                 catch(Exception e) 
                       {
                        e.printStackTrace();
                     }
                        disp.close();
        }
                           public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                            doGet(rq,rp);
                           }
  }
WEB.XML
<servlet>
   <servlet-name>MySqlCurrTime</servlet-name>
   <servlet-class>MySqlCurrTime</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCurrTime</servlet-name>
   <url-pattern>/MySqlCurrTime</url-pattern>
</servlet-mapping>

MySql CurrDate Function in Java Servlet

By Dinesh Thakur

This Function will represent the current date on the web browser.

first i make a table in database named ‘dbase’ with required fields and values which is under the reference of mySql(php myAdmin). Here i import all mandatory java package from the java library as program needs. Then after i make a class named ‘MySqlCurrDate’ extends ‘HttpServlet’. And here i use serviceMethod() which will get request from the doGet()Method for getting output on the web browser. After i load all the required drivers for accessing database. After then i declare mandatory variables like i declare ‘Connection’ this variable does the job to create a link between database and the actual code. The other one i declare is ‘resultSet’ that will fetch the value from selected column and rows. Now here i declare the ‘preparedStatement’ that will use to execute the selected query like executeQuery() as (Select CURDATE() AS today). Here i use the doGet()Method for output on a web browser.

For getting the output in the tabular form i use ‘HTML’ code and tags that will show output in a manner way on web browser. 

  
EXAMPLE
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCurrDate extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
   {
      rp.setContentType("text/html");
      PrintWriter disp = rp.getWriter();
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost/dbase";
      String uid = "root";
      String psw = "root";
      Connection con=null;
      PreparedStatement ps = null;
      ResultSet rs;
      try
       {
         Class.forName(driver);
         con = DriverManager.getConnection(url,uid,psw);
         ps=con.prepareStatement("Select CURDATE() AS today");
         rs = ps.executeQuery();
             String title = "Using Current Function";
         String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
             "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Current Date  </th>\n"+ "</body> </html>");
         while(rs.next())
           {
             String curr = rs.getString(1);
                 disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
           }     
       }  
                 catch(Exception e) 
                        {
                           e.printStackTrace();
                        }
                           disp.close();
    }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                                 doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlCurrDate</servlet-name>
   <servlet-class>MySqlCurrDate</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCurrDate</servlet-name>
   <url-pattern>/MySqlCurrDate</url-pattern>
</servlet-mapping>

MySql COT Function in Java Servlet Example

By Dinesh Thakur

The Function ‘COT'(Cotangent) will return the cotangent value.

I make a table in database named ‘dbase’ which is been created in the reference of mySql(php myAdmin).then i import all the required java packages from java library as required from program need. Then i make a class named ‘MySqlCOTFunction’ extends ‘HttpServlet’. After that i use serviceMethod()that will get request from doGet()method for output on the web browser. Before declaring the variables as required i loaded all the mandatory drivers for database accessing. Here i declare ‘Connection’ this variable will be the responsible for the making bridge or path between the database and the java code. The other one will be the ‘resultSet’ this one will help to fetch the values from the selected columns and the rows. Here i declare ‘preparedStatement’ this will bring execute the selected query like executeQuery as (Select COT(’60’)). Here i use doGet()Method that will bring the output on the web browser.

to get output on the web browser in a tabular form i use ‘HTML’ code and tag which bring output in a manner way. 

 
EXAMPLE
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCOTFunction extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
   {
      rp.setContentType("text/html");
      PrintWriter disp = rp.getWriter();
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost/dbase";
      String uid = "root";
      String psw = "root";
      Connection con=null;
      PreparedStatement ps = null;
      ResultSet rs;
      try
       {
         Class.forName(driver);
         con = DriverManager.getConnection(url,uid,psw);
         ps=con.prepareStatement("Select COT('60')");
         rs = ps.executeQuery();
             String title = "Using COT Function";
         String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
             "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
         while(rs.next())
           {
              String val = rs.getString(1);
                  disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
           }     
       }  
                  catch(Exception e) 
                        {
                          e.printStackTrace();
                        }
                          disp.close();
   }
                      public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                        {
                              doGet(rq,rp);
                        }
}
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlCOTFunction</servlet-name>
   <servlet-class>MySqlCOTFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCOTFunction</servlet-name>
   <url-pattern>/MySqlCOTFunction</url-pattern>
</servlet-mapping>

MySql COS Function in Java Servlet

By Dinesh Thakur

The Function ‘COS'(Cosine) will return the cosine value of any radian expression.

i make a table in database named ‘dbase’ with required fields and values in it. Database is been created in the reference of mySql(php myAdmin). Here i import all the java packages required during the program from java library. Then i make a class named ‘MySqlCOSFunction’ extends the ‘HttpServlet’. Here i use serviceMethod() which will bring the request from doGet()Method for Output. Here the next step will be to loaded all required drivers for database accessing. Now i will declare the mandatory variables like ‘connection’ this variable will take over to create a link between the database and the java code. The next one will be the ‘resultSet’ this variable will use to retrieve the value from columns and rows as required the query.the other one will be the ‘preparedStatement’ this variable is must use for the executing selected query like executeQuery as (Select COS(’60’)). Here i use doGet()Method for getting output on the web Browser.

To get output on the web browser i use ‘HTML’ code and tags that will present the output in a tabular form on the web browser.

EXAMPLE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCOSFunction extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
   {
      rp.setContentType("text/html");
      PrintWriter disp = rp.getWriter();
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost/dbase";
      String uid = "root";
      String psw = "root";
      Connection con=null;
      PreparedStatement ps = null;
      ResultSet rs;
      try
        {
          Class.forName(driver);
          con = DriverManager.getConnection(url,uid,psw);
          ps=con.prepareStatement("Select COS('60')");
          rs = ps.executeQuery();
              String title = "Using COS Function";
          String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
              disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
          "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
              "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
          while(rs.next())
            {
              String val = rs.getString(1);
                  disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
            }     
            }         
                  catch(Exception e) 
                         {
                            e.printStackTrace();
                         }
                            disp.close();
    }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                                 doGet(rq,rp);
                           }
}
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlCOSFunction</servlet-name>
   <servlet-class>MySqlCOSFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCOSFunction</servlet-name>
   <url-pattern>/MySqlCOSFunction</url-pattern>
</servlet-mapping>

MySql CONV Function in Servlet

By Dinesh Thakur

The Function ‘CONV’ will convert numbers between Number bases.

i make a table in database named ‘dbase’ with required fields and values too. The database made within the reference of mySql(php myAdmin). Then i import all the required java packages from java library with required Condition. I made a class named ‘MySqlCONVFunction’ which extends ‘HttpServlet’. Here now i use serviceMethod() which will act a role of getting request from doGet()Method for output. Before declaring the variable i loaded here all required drivers for the database accessing. Here now time to declaring the variables i declare ‘connection’ this variable will use to create the link between database and the actual code. The other i declare is ‘resultSet’ this will use to fetch the value from required columns and rows as required condition. Here i also declare ‘preparedStatement’ this will get in the use to executing the selected Query like executeQuery() as (Select CONV(5,17,9)). Here in the last instance of coding i just use doGet()method which will bring the output on the web browser.

While the programming i use ‘HTML’ code or tags to bring output in tabular form on the web Browser. 

  
EXAMPLE
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlCONVFunction extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
    {
      rp.setContentType("text/html");
      PrintWriter disp = rp.getWriter();
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost/dbase";
      String uid = "root";
      String psw = "root";
      Connection con=null;
      PreparedStatement ps = null;
      ResultSet rs;
      try
       {
         Class.forName(driver);
         con = DriverManager.getConnection(url,uid,psw);
         ps=con.prepareStatement("Select CONV(5,17,9)");
         rs = ps.executeQuery();
             String title = "Using CONV Function";
         String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
             "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
         while(rs.next())
           {
             String val = rs.getString(1);
                 disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );  
           }     
       }  
                 catch(Exception e) 
                        {
                           e.printStackTrace();
                        }
                           disp.close();
     }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                                 doGet(rq,rp);
                           }
 }
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlCONVFunction</servlet-name>
   <servlet-class>MySqlCONVFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlCONVFunction</servlet-name>
   <url-pattern>/MySqlCONVFunction</url-pattern>
</servlet-mapping>

MySql ConvertTime Zone Servlet Example

By Dinesh Thakur

The function ‘CONVERT_TZ’ will convert the regional time zone as required.

The first i make a table in database named ‘dbase’ with the required fields and value in it database is been created with the reference of mySql(php myAdmin).then i import all the required java packages from java library according to the program need. I made a class named ‘MySqlConvertTimeZone’ completely extends ‘HttpServlet’. Then i use the serviceMethod() which use to getting request from doGet()Method. Here i loaded all the required drivers for database accessing. after that i declare mandatory variables for database conditions. Like i declare ‘Connection’ this variable will use to create a link between database and the java code. The other one will be the ‘resultSet’ this will be the responsible for the fetching value from the selected columns and rows. The next variable will be the ‘preparedStatement’ this variable is been used to executing the selected query like executeQuery() as (SELECT CONVERT_TZ(‘2014-05-30 11:03:00′,’IST’,’GMT’). Now here i use doGet()method which will bring the output on web browser.

To getting output in a manner way or in impressive look i use some of ‘HTML’ tags that are present the output in tabular form on the web browser.

 

EXAMLPE 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlConvertTimeZone extends HttpServlet
 {
   public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
   {
      rp.setContentType("text/html");
      PrintWriter disp = rp.getWriter();
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://localhost/dbase";
      String uid = "root";
      String psw = "root";
      Connection con=null;
      PreparedStatement ps = null;
      ResultSet rs;
      try
       {
         Class.forName(driver);
         con = DriverManager.getConnection(url,uid,psw);
         ps=con.prepareStatement("SELECT CONVERT_TZ('2014-05-30 11:03:00','IST','GMT')");
         rs = ps.executeQuery();
             String title = "To Convert Time Zone";
         String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
             disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
             "<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Desired Time  </th>\n"+ "</body> </html>");
         while(rs.next())
           {
             String curr = rs.getString(1);
                 disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );  
           }     
            }         
                 catch(Exception e) 
                        {
                           e.printStackTrace();
                        }
                           disp.close();
     }
                       public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
                           {
                                  doGet(rq,rp);
                           }
}
 
WEB.XML
 
<servlet>
   <servlet-name>MySqlConvertTimeZone</servlet-name>
   <servlet-class>MySqlConvertTimeZone</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
   <servlet-name>MySqlConvertTimeZone</servlet-name>
   <url-pattern>/MySqlConvertTimeZone</url-pattern>
</servlet-mapping>
« Previous Page
Next Page »

Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW