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());
  }
}

Leave a reply