Tuesday 10 September 2013

Accessing Database in Java Servlet and JDBC Connection

 Here we are going to show how to access Database in case of Servlets very effective way
you can do insertion,updation in similar manner. 

 
// Loading libraries that we will use
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
public class DatabaseAccess extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // JDBC driver name, database URL,Username and password
      static final String JDBC_DRIVER="com.mysql.jdbc.Driver";  
      static final String DB_URL="jdbc:mysql://localhost/TEST";
      static final String USER = "root";
      static final String PASS = "password";

      // Set response 
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Database Result";
      String docType =
        "<!doctype html public \"-//w3c//dtd html 4.0 " +
         "transitional//en\">\n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n");
      try{//Here see the steps for JDBC Connection in BOLD
         // Register JDBC driver
         Class.forName("com.mysql.jdbc.Driver");

         // Openning  a connection
         conn = DriverManager.getConnection(DB_URL,USER,PASS);

         // Executing  SQL query
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, first, last, age FROM Employees";
         ResultSet rs = stmt.executeQuery(sql);

         // Extracting data from result set
         while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String name = rs.getString("name");
           

            //Display values
            out.println("ID: " + id + "<br>");
            out.println(", Age: " + age + "<br>");
            out.println(", name: " + name + "<br>");
           
         }
         out.println("</body></html>");

         // Clean-up environment
         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         //Handle errors for JDBC
         se.printStackTrace();
      }catch(Exception e){
         //Handle errors for Class.forName
         e.printStackTrace();
      }finally{
         //finally block used to close resources
         try{
            if(stmt!=null)
               stmt.close();
         }catch(SQLException se2){
         }
         try{
            if(conn!=null)
            conn.close();
         }catch(SQLException se){
            se.printStackTrace();
         }
      }
   }
}

Types of JDBC Connection In Java

JDBC Connection is a connection pool in order to interact with the database whether simple or distributed database.
There are 5 types of Jdbc Driver:

1.JDBC-ODBC Driver:
Java Database Connectivity -Oracle Database Connectivity is a type 1 driver used in earlier times and now we use just used it  for testing purposes.
Simple architecture where we have: Java Application calling>>JDBC API>>JDBC Driver Manager>>JDBC ODBC Bridge>>ODBC Driver>> Database Library API>>Database.
Overhead due to ODBC connection and ODBC need to be on client machine or need to install it.

2.Type 2 Driver- Native API Driver:
These Driver converts jdbc calls into native calls of the database apis.It is a database driven implementation that uses client side libraries of the database.
Simple Architecture Where we have:Java Application Calling>>JDBC API>>JDBC Driver Manager>>Native API Driver>>Database Library API>>Database.
IT is faster than Type 1 as there is no requirement for ODBC connection.
It is platform independent and support all application excepts applet.

 3.Type 3 Driver Network Protocol Driver:
These driver is also known as pure java Driver for Database Middleware is a database driven implementation which makes use of middle tier between calling program and database.
The JDBC client driver written in java communicate with the net server using a database independent protocol then net server translates this into database command for fetching or update operation on database
Simple Architecture:
Java application call>>Java API>>JDBC Driver Manager>>Network Protocol Driver>>Middle ware>>Distributed Database.

4.Type 4 Driver Pure Java Driver:
Most importantly used by all the organization as it is a pure Java Driver that converts java calls into data specific calls and get required results with no pain and ease of use while connecting.
These Driver is Database Depentdent only drawback .
Simple Architecture:
Java application call>>Java API>>JDBC Driver Manager>>Network Protocol Driver>>Distributed Database.

5.Type 5 Driver :
 IT is a new driver which eradicate the limitations of type 4 and hence 100% client side single tier .
It eliminates unrestricted performance,codeless enhancement,all in one deployment,resource efficiency.




What is Static Keyword?

In Java,Static Keyword is associated with the class not with the instance of class.Therefore you can access static member without creating a class instance.
There are two types of static members in C++ and Java:
1.Static field:
The value of static field remains same for all the instance of the class.You can interchange the position of static keyword as per your need.Between the function calls its value remains same.
1.1Like: public static int a ;
1.2 static public int a;
Both the statement is same 1.1 and 1.2
If a class has static field StudentId all the objects within the class will have same value for StudentId in the program.It will help in counting the number of objects.
Static field will be accessed by classname.
classname.<static variablename>.
  
Static fields are created and initialized when the class is first loaded.

2.Static Method():
A method declares as static becomes static method which can access only static variables.
Static method is associated with the class not with the instance or object of the class.
Static method we see in our program that is main()which is called by the java runtime to execute an application.
In order to call static method:
classname.staticmethodname();///Sytax for call static method.

Simple Program in Showing USe of Static:
class A
{
int a =10;
static int b=10;
void display()
{a=a+a;
b=b+b;
System.out.println("a");
System.out.println("b");
}
}
public class C
{
public static void main(String args[])
{
A d=new A();
d.display();
A e=new A();

e.display();
}

OUTPUT:
20
20
20
40

System.out.Println Java


We usually use many or dozen of times but do we really know what it is.
System.out.println() just prints the argument passed  into the System.out.

System.out.println():
1.System: It is a final class and cannot be inherited .For further know-how refer to javadocs.
2.out: It is of type PrintStream and static menber of System Class.The Access specifiers for it is public final.
3.println():As braces itself says that it is a function that print whatever pass to it in the standard console.
 Every println makes a call to print method and print calls to write method .

A simple program to print Hello using System.out.println():
class a
{
public static void main(Strings args[])
{
System.out.println("Hello") ;
}
}
Compile:javac a.java
run:java a