Wednesday, May 5, 2010

Another Id generater method

//////////call method//////////////
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

String reqid = new IdGenerator().getDateFormatedNextId("tbl_travel_package_req", "TPR-"+sdf.format(new Date()), "req_id", 3);


////////////////////////////



/////Method defination//////////////
public String getDateFormatedNextId(String tableName,String prefix,String columnName, int padlen)throws Exception
{
//create the connection of database.
int temp=0;
Connection con = null;
try{
con=new DBConnection().getDBConnection();
con.setAutoCommit(false);
Statement stmt=con.createStatement(); // getCon() is the return type of created Connection.
ResultSet rs=stmt.executeQuery("Select max(cast(SUBSTRING_INDEX("+columnName.trim()+",'/',-1) as unsigned int )) from "+tableName.trim()+" where SUBSTRING_INDEX("+columnName.trim()+",'/',1)='"+prefix.trim()+"'");

if(rs.next())
{
String str = rs.getString(1);
if(str != null)
{
temp=Integer.parseInt(str);
}

}

++temp;

String new_no = ""+temp;
prefix +="/";
for(int i = new_no.trim().length();i<padlen;i++)
{
prefix =prefix.trim()+"0";
}
rs.close();
stmt.close();
con.commit();
}catch(Exception e){
if(con != null){
con.rollback();
}
throw e;
}
finally
{
con.setAutoCommit(true);
}

con.close();
next_id=prefix.trim()+(temp);

return next_id;
}

No comments:

Post a Comment