Saturday 20 February 2016

Database connection in java with it's example

## Database Connection: 

There are few step's to how to get connection MySql database and also explain with example.



Five step of Database connection



Step 1: Drive class: It means drive class for the mysql database is Class.forName("com.mysql.jdbc.Drive"); 


Step 2: Connection Url:   It means the connection URL for the database is 
connection con=DriverManager.getConnection("jdbc://localhost:3306/Database","UserName","Password");


Step 3: UserName: UserName is root default for the mysql database.


Step 4: Password: Here Password is provided by the user at time of installing the mysql database.






Here we put it's  example for how to connect your database


import java.sql.*;

class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
 
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");

//Please enter in place of demo your database name, root is username and password

 //create database statement
Statement stmt=con.createStatement();
 
ResultSet rs=stmt.executeQuery("select * from admin");

// Here enter in place of admin your class name.
 
while(rs.next())
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
 
con.close();
 
}
catch(Exception e)
{
         System.out.println(e);
}
 
}

}

Result : Now your database is sucessfully conected with mysql database. now here you and do any thing like update, delete...etc



Use of response.sendRedirect with example

# Use of response.sendRedirect() 

Use of response.sendRedirect() is method of HttpServletResponse. It interface can be used to redirect to another resource, It may, jsp or html file. It's is most useful for you.




Example:-




package com;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;
import java.sql.PreparedStatement;




/**
 *
 * @author pradeep
 */
public class LoginServlet extends HttpServlet 
{

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
{
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) 
{
           String id=request.getParameter("t1");
            String name=request.getParameter("t2");
            
            
            Class.forName("com.mysql.jdbc.Driver");
             
            //make connection       
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseName","root","root");
                    
            //create or udate database statement
            PreparedStatement stmt=con.prepareStatement("select * from admin where id=? and name=?");
            stmt.setString(1, id);
            stmt.setString(2, name);
            ResultSet rs=stmt.executeQuery();
                   //stmt.execute("insert into student values('1','a')");

                   if(rs.next())
                   {
                       out.println("<font color='green'>Welcome ADMIN</font>");
                       out.println("bb");
                   //response.sendRedirect("index.html");
                   }
                       else
                       out.println("<font color='red'>error</font>");
          
        }
        catch(Exception e){}
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
{
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
{

        processRequest(request, response);

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() 
{
        return "Short description";
    }// </editor-fold>

}



How to set visitor counter in your website its coding

If you want to on your website visitor counter then it means count online user which access your websites at current time in servlet. you are set in your website very easy you can see my example below.


For Example:-



I am provide for you some codes just copy and paste where you want to set your visitor counter this is very useful for you.


 ServletContext ctx = getServletContext();
           Integer count = (Integer)ctx.getAttribute("count");
           if(count == null)
           {
               count = new Integer(0);
           }
           count = new Integer(count.intValue()+1);
           ctx.setAttribute("count", count);
           out.println("Visitor count: " +count+"");


Note: If you are create .jsp page then this code is valid or if you are create .java class then you are just change some code. replace out.println("Visitor count:" +count+""); into System.out.println("Visitor count: " +count+"");



Note : If you have any problem then reply me.

Method overloading or function overloading with example


Function overloading if we have more than one function having same name with different prototypes (parameters) then it is also called function overloading.





For Example:-

package myblogs;


/**

 *
 * @author pradeep
 */
class DemoOverloading 
{
   int height;
   DemoOverloading() 
    {
      System.out.println("Demo overloading");
      height = 0;
    }
   DemoOverloading(int i) 
     {
        System.out.println("Mobile phone tower Height "
      + i + " big tall");
        height = i;
     }
        void info() 
           {
                System.out.println("Building is" + height
      + " big tall");
           }
        void info(String s) 
          {
                System.out.println(s + ": Building is "
      + height + " big tall");
          }
}
public class MainDemoOverloading 
  {
   public static void main(String[] args) 
    {
      DemoOverloading t = new DemoOverloading(0);
      t.info();
      t.info("Function overloaded method");
      // Function Overloaded constructor
      new DemoOverloading();
   }
}



Result: Output of this program is:


Mobile phone tower Height 0 big tall

Building is 0 big tall
Function overloaded method: Building is 0 big tall
Demo overloading

BUILD SUCCESSFUL (total time: 1 second)

Note: If you have any problem then reply me.


Method overriding or Function overriding with example

Function overriding is just easy to say if sub class or child class has the same method or function declared in the parent class that types of method is called function or method overriding.

Declaring a method in subclass (child class) which function is already  declared in  parent class is known as method overriding.


For Example:-


/**
 *
 * @author pradeep
 */
class HumanBeing
{
   public void social()
   {
      System.out.println("Human is eating");
   }
}
class Boy extends HumanBeing{
   public void social(){
      System.out.println("Boy is eating");
   }
   public static void main( String args[]) 
{
      Boy obj = new Boy();
      obj.social();
   }
}




Result:Result of this program is

run:
Boy is eating
BUILD SUCCESSFUL (total time: 0 seconds)

Note: If you have any problem then reply me.




What is an Array in java with example

Array is collection of similar kind of data. Array in java is index based , first element of the array is stored at 0 index.






Benefits (Advantages) of array:-

  1.  Code Optimization
  2.  Performance increase




Disadvantage Disadvantage of array is "size limit ".




Types of array:

  1. Single Dimensional Array 
  2. Multidimensional Array




Many types of syntax to declared in array:

  1. dataType[] arr; (or)  
  2. dataType []arr; (or)  
  3. dataType arr[];  


1 Example of single Dimensional array



/**

 *

 * @author pradeep

 */

class ArrayDemo {

    public static void main(String[] args) {

        /*int marks[]=new int[5];

        marks[0]=33;

        marks[1]=65;

        marks[2]=69;

        marks[3]=78;

        marks[4]=86;

        * */

        //int marks[]=new int[]{33,65,69,78,86};

        int marks[]={33,65,69,78,86};

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

        {

            System.out.println("print marks:"+marks[i]);

        }

    }

    

}



2. Example of MultiDimensional array

/**
 *
 * @author pradeep
 */


class MultiDimensionalArray{  
public static void main(String args[]){  
  
//declaring and initializing 2D array  
int array[][]={{6,7,8},{4,6,8},{3,6,9}};  
  
//printing 2D array  
for(int i=0;i<3;i++){  
 for(int j=0;j<3;j++){  
   System.out.print("Multi Dimensional Array" +array[i][j]+" ");  
 }  
 System.out.println();  
}  
  
}}  

Result: Output of this result is:



run:

Multi Dimensional Array6 Multi Dimensional Array7 Multi Dimensional Array8 

Multi Dimensional Array4 Multi Dimensional Array6 Multi Dimensional Array8 

Multi Dimensional Array3 Multi Dimensional Array6 Multi Dimensional Array9 

BUILD SUCCESSFUL (total time: 0 seconds)







Note: If you have any problem then reply me.

StringBuffer in java with examples

Java stringBuffer class is used to created mutable string. The string java is same as string class except it is mutable that us can be changed.

String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).


StringBuffer Functions:- The following program explains the usage of the some of the basic StringBuffer methods like ;





  1. capacity() Returns the current capacity of the String buffer.
  2.  length() Returns the length (character count) of this string buffer.
  3. charAt(int index) The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
  4. setCharAt(int index, char ch) The character at the specified index of this string buffer is set to ch.
  5. toString() Converts to a string representing the data in this string buffer.
  6.  insert(int offset, char c) Inserts the string representation of the char argument into this string buffer.
  7. delete(int start, int end) Removes the characters in a substring of this StringBuffer
  8. replace(int start, int end, String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String.
  9. reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence.
  10. append(String str) Appends the string to this string buffer.
  11. setLength(int newLength).




Note 


  1. That the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
  2. That the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.





For Example:-





/**
 *
 * @author pradeep
 */

public class DemoStringBuffer 
{

public static void main(String[] args)
 {
//     Examples of Creation of StringsBuffer
StringBuffer strBuff1 = new StringBuffer("Bob");
StringBuffer strBuff2 = new StringBuffer(400); //With capacity 100
StringBuffer strBuff3 = new StringBuffer(); //Default Capacity 16
System.out.println("stringBuffer1 : " + strBuff1);
System.out.println("stringBuffer2 capacity : " + strBuff2.capacity());
System.out.println("stringBuffer3 capacity : " + strBuff3.capacity());
}
}







Result:  Output of this program is:





run:


stringBuffer1 : Bob


stringBuffer2 capacity : 400


stringBuffer3 capacity : 16

BUILD SUCCESSFUL (total time: 1 second)





Note: If you have any problem then reply me.