Creating Database Connection in Context.xml

<Context>
  <Resource name="jdbc/[YourDatabaseName]"  auth="Container" type="javax.sql.DataSource"
   username="[DatabaseUsername]" password="[DatabasePassword]" driverClassName="com.mysql.jdbc.Driver"
   url="jdbc:mysql:/[yourserver]:3306/[yourapplication]" maxActive="15" maxIdle="3"/>
</Context>

context.xml

<Context>
  <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/test"/>
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Test.java

 PrintWriter out = response.getWriter();
 String Sno = request.getParameter("t1");
 String Name = request.getParameter("t2");
		
 try{
   InitialContext context = new InitialContext();
   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/test");
   Connection conn  = ds.getConnection();
   PreparedStatement statement = conn.prepareStatement("insert into Details values(?,?)");
   statement.setString(1, Sno);
   statement.setString(2, Name);
   statement.execute();
   conn.close();
   statement.close();
   out.println("Done");
  }catch (Exception e) {
   e.printStackTrace();
  }

executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

public class Database 
{
    private static DataSource dataSource;

    static 
    {
        try 
        {
          dataSource = new InitialContext().lookup("jndifordbconc");
        }catch (NamingException e) 
        { 
          throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
        }
    }

    public static Connection getConnection() 
    {
      return dataSource.getConnection();
    }
}

public List<Entity> list() throws SQLException 
{
    Connection        connection = null;
    PreparedStatement statement  = null;
    ResultSet         resultSet  = null;
    List<Entity>      entities   = new ArrayList<Entity>();

    try 
    {
        connection = Database.getConnection();
        statement  = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        resultSet  = statement.executeQuery();

        while (resultSet.next()) 
        {
            Entity entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setFoo(resultSet.getString("foo"));
            entity.setBar(resultSet.getString("bar"));
            entities.add(entity);
         }
    } 
    finally 
    {
        if (resultSet  != null) try { resultSet.close();  } catch (SQLException ignore) {}
        if (statement  != null) try { statement.close();  } catch (SQLException ignore) {}
        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
    }
    return entities;
}
package com.javadb2.mugil.employee;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.javadb2.mugil.db.display;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class update
{	 
	public static void main(String args[])
	{
	  bean objBean = new bean();
	  objBean.setEmpId(Integer.parseInt(getInput("Enter Employee Id :")));
	  objBean.setEmpName((String)getInput("Enter Employee Name:"));
	  objBean.setEmpSalary(Integer.parseInt(getInput("Salary")));
	  updateValues(objBean);
	}
	
	public static void updateValues(bean objBean)
	{	
		System.out.println(objBean.getEmpName());
		System.out.println(objBean.getEmpSalary());
		
		String strSQL = "UPDATE employeelist" +
				"   SET empname = ? ," +
				"       salary  = ?" +
				" WHERE empid = ?";
		
		try 
		{
			Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "pass");
			PreparedStatement stmt = (PreparedStatement) conn.prepareStatement(strSQL);
			
			stmt.setString(1, objBean.getEmpName());
			stmt.setDouble(2, objBean.getEmpSalary());
			stmt.setInt(3, objBean.getEmpId());
			
			int affected = stmt.executeUpdate();
						
			if(affected == 1)
			{
 			  System.out.println("Updated Successfully");
			}
			else
			{
			  System.err.println("Unable to Update Employee");
			}
		} 
		catch (SQLException e) 
		{
		  e.printStackTrace();
		}
	}

	public static String getInput(String prompt)
	{
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		
		System.out.print(prompt);
		System.out.flush();
		
		try 
		{
			return stdin.readLine();
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			return e.getMessage();
		}
	}
}	

Database Table

 CREATE TABLE employeeList(empid int not null primary key auto_increment,
                           empname varchar(255),
                           salary  double);

Bean Class

package com.javadb2.mugil.employee;

public class bean
{
  private int  empId;
  private String  empName;
  private double  empSalary;
	
  public int getEmpId() 
  {
    return empId;
  }
	
  public void setEmpId(int empId) 
  {
    this.empId = empId;
  }
	
  public String getEmpName() 
  {
    return empName;
  }
  
  public void setEmpName(String empName) 
  {
    this.empName = empName;
  }
  
  public double getEmpSalary() 
  {
    return empSalary;
  }

  public void setEmpSalary(double empSalary) 
  {
    this.empSalary = empSalary;
  }
}

Crud Operation with Bean Class

 package com.javadb2.mugil.employee;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.javadb2.mugil.db.display;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;

public class insert
{	
  public static void main(String[] args) 
  {
    bean objBean = new bean();
		
    objBean.setEmpName(display.getInput("Enter the Employee Name"));
    objBean.setEmpSalary(Integer.parseInt(display.getInput("Enter Salary")));
		
    boolean result = getInsertedKey(objBean);
		
    if(result)
    {
      System.out.println("The Last Inserted Primary Key is "+objBean.getEmpId());			 
    }
   }
	
   public static boolean getInsertedKey(bean objBean)
   {	
     ResultSet keys = null;
		
     String strSQL = "INSERT INTO employeeList(empname, salary)VALUES(?,?)";		
		
     try 
     {
	Connection conn 	= getConnection();
	PreparedStatement stmt 	= (PreparedStatement) conn.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS);
			
	stmt.setString(1, objBean.getEmpName());
	stmt.setDouble(2, objBean.getEmpSalary());
			
	int affected = stmt.executeUpdate();
			
	if(affected == 1)
	{
  	   keys = stmt.getGeneratedKeys();
	   keys.next();
	   int newkey = keys.getInt(1);
	   objBean.setEmpId(newkey);
	}
	else
	{
	   System.err.println("Unable to Update Values");
	   return false;
	}
      }
      catch (SQLException e) 
      {
	 processException(e);
	 System.err.println("Error in Establishing Connection");
      }
		
      return true;
  }
	
  public static Connection getConnection() throws SQLException
  {
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "pass");
    return conn;
  }
	
  public static void processException(SQLException e)
  {
     System.err.println("Error Message "+e.getMessage());
     System.err.println("Error Code"+e.getErrorCode());
     System.err.println("SQL State"+e.getSQLState());
  }
}
 public class JAVADB2
 {
   public static void main(String args[]) throws SQLException 
   {	
     try	
     {
	Connection conn = null;		
	ResultSet  rs 	= null;
	Statement  stmt	= null;
			
	String strSQL = "SELECT * FROM employee";
	conn = incDB.getConnection();
	stmt = (Statement)conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.FETCH_FORWARD);			
			
 	rs = stmt.executeQuery(strSQL);			
	display.getRecords(rs);
      } 
      catch (SQLException e) 
      {
	incDB.getException(e);
      }
    }	
}
Utility Methods
 public class incDB
{	
	private static String USER_NAME = "root";
	private static String USER_PASS = "pass";
	private static String CONN_STRING = "jdbc:mysql://localhost/test";
	
	public static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(CONN_STRING, USER_NAME, USER_PASS);
	}
	
	public static void getException(SQLException e)
	{
		System.out.println("Message :"+e.getMessage());
		System.out.println("Error Code :"+e.getErrorCode());
		System.out.println("State : "+e.getSQLState());
	}
}

public class incDB
{	
	private static String USER_NAME = "root";
	private static String USER_PASS = "";
	private static String CONN_STRING = "jdbc:mysql://localhost/test";
	
	public static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(CONN_STRING, USER_NAME, USER_PASS);
	}
	
	public static void getException(SQLException e)
	{
		System.out.println("Message :"+e.getMessage());
		System.out.println("Error Code :"+e.getErrorCode());
		System.out.println("State : "+e.getSQLState());
	}
}

Stored Procedure

  DROP PROCEDURE IF EXISTS getEmpDetail;
  CREATE PROCEDURE getEmpDetail(IN Salary INT)
  BEGIN   
   SELECT empid, empname, sal
     FROM employee
    WHERE sal < Salary;
  END;

Java Code

public static void main(String args[]) throws SQLException 
{	
  try	
  {
    Connection conn = null;		
    ResultSet  rs   = null;
			
    Integer salary = Integer.parseInt(display.getInput("Enter the Salary Amount"));
			
    String strSQL = "{CALL getEmpDetail(?)}";
    conn = incDB.getConnection();
    PreparedStatement stmt = (PreparedStatement) conn.prepareStatement(strSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.FETCH_FORWARD);			
    
    stmt.setInt(1, salary);
    rs = stmt.executeQuery();
		
    display.getRecords(rs);
  } 
  catch (SQLException e) 
  {
    incDB.getException(e);
  }
}	

Utility Function

 public class incDB
{	
	private static String USER_NAME = "root";
	private static String USER_PASS = "pass";
	private static String CONN_STRING = "jdbc:mysql://localhost/test";
	
	public static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(CONN_STRING, USER_NAME, USER_PASS);
	}
	
	public static void getException(SQLException e)
	{
		System.out.println("Message :"+e.getMessage());
		System.out.println("Error Code :"+e.getErrorCode());
		System.out.println("State : "+e.getSQLState());
	}
}

public static void getRecords(ResultSet rs) throws SQLException 
{	
  while(rs.next())
  {
    StringBuffer buffer =  new StringBuffer();
    buffer.append("Emp Id :"+ rs.getString("empid")+ " Emp Name :"+rs.getString("empname"));
    System.out.println(buffer.toString());
  }
		
  if(rs.isBeforeFirst())
    System.out.println("Finished Printing");
 }
	
 public static String getInput(String prompt)
 {
   BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
   System.out.print(prompt);
   System.out.flush();
	
   try 
   {
     return stdin.readLine();
   } 
   catch (Exception e) 
   {
     return "Error :"+e.getMessage();
   }
  }

Stored Procedure

 DROP PROCEDURE IF EXISTS getEmpDetails;
CREATE PROCEDURE getEmpDetails(IN Salary INT, OUT total INT)
BEGIN   
   SELECT count(*) into total
    FROM employee
   WHERE sal < Salary;
  SELECT empid, empname, sal
    FROM employee
   WHERE sal < Salary;
END;

Java Code

public static void main(String args[]) throws SQLException 
{	
  try	
  {
     Connection conn = null;		
     ResultSet  rs   = null;
			
     Integer salary = Integer.parseInt(display.getInput("Enter the Salary Amount"));			
     String strSQL  = "{CALL getEmpDetails(?, ?)}";
     conn           = incDB.getConnection();
     java.sql.CallableStatement stmt = conn.prepareCall(strSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.FETCH_FORWARD);			
     stmt.setInt(1, salary);
     stmt.registerOutParameter("total", Types.INTEGER);
			
     rs        = stmt.executeQuery();
     int nRows = stmt.getInt("total");
			
     System.out.println("Total no of Records :"+nRows);
     display.getRecords(rs);
  } 
  catch (SQLException e) 
  {
     incDB.getException(e);
  }
}	

Utility Functions

public static void getRecords(ResultSet rs) throws SQLException 
{	
   while(rs.next())
   {
     StringBuffer buffer =  new StringBuffer();
     buffer.append("Emp Id :"+ rs.getString("empid")+ " Emp Name :"+rs.getString("empname"));
     System.out.println(buffer.toString());
   }
		
    if(rs.isBeforeFirst())
      System.out.println("Finished Printing");		
}