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

Friday 17 May 2013

Java Projects Java Assignment

Java is not a language it is technology when we talk about java we should know what we can do through Java,how prowerful and secure it is and what constraints and checkpoints we can add to our Webapp,Software or mobile apps in an effective manner.
Java is having three main Edition:
1.Java 2 Standard Edition: (J2SE)
What we can make and Learn in this through this we can make an standalone program like an inventory system or tracking system for a shop,offfice or any manufacturing industry.Simple Standalone application that we can make by using Swing,JDBC and Sqlite as required for our initial Project.
2.Java 2 Enterprise Edition:(J2EE)
When we talk about Enterprise Edition we are mostly talking ERP for a Company,Any Web Based management project by using mutli layer and in depth architecture for development.Here generally we talk about HTML,CSS,Javascript For GUI,JSP,Servlet,Struts,Spring,Design Patterns,Php In java,Ruby in Java and mobile based customization so to have more value to our project.
Simply it is an online Meeting System,Online Banking Management Project etc as this project requires to think in more depth manner by keeping in mind security as first Priority.
Here We can Use Various CMS like Sharepoint,Hippo,OpenCMS,Liferay etc.
3.Java 2 Micro Edition:(J2ME):JAVAME
We are talking about here our mobile portion and there connection with server in order to develop our mobile games,mobile apps  for fun and learning,for security purposes.
It include  each and every section of mobile part and developing it more securily by using Java Technology in an meaningful manner.For Set-top boxes,blu-ray Disc Players etc.
Here we generally use:Java ,SQlite,XML,python etc.


FOR Project or Assignment Help You can contact to our Java Experts at LearnProgramm@gmail.com.
https://www.google.co.in 
https://www.yahoo.com
https://www.twitter.com
https://www.Facebook.com
https://www.w3schools.com
https://www.youtube.com



Monday 22 August 2011

prime in java


to calculate whether the number is prime or not.prime in java
javalearing.blogspot.com
class prime
{
public static void main(String args[])
{


int num=11;
int i;
for( i=2;i<num;i++)
{
int n=num%i;
if(n==0)
{
System.out.println("not prime");
break;
}
}
if(i==num){
System.out.println("prime number");
}
 }   }

package implementation in java

javalearing.blogspot.com
Here we will show u a simple program of packages and its implementation.
first create a package naming pack(any name)then create class and its method should be static and public  as shown  below:


package pack;
public class hemant
{
public static void show(String s)
{
    System.out.println(s);
    }
    }
save above as hemant.java
now compile your file as: javac hemant.java
now make another file in which you wanted to import your package for example demo.java

import pack.hemant; //for importing package pack having class name hemant
class demo
{
public static void main(String args[])
{
hemant.show("hi bye");
}
}
save above as demo.java
compile your package class first:        javac hemant.java
compile your another file create by you: javac demo.java
run your demo file:java demo
output:
hi bye
finally you get the clear concept of packages.