Search Your Question

Tuesday, May 19, 2009

Generate new ID from a database table in java

/*
* This is the class which create a new Unique ID for a database Table.
* It takes three Parameter.
* tableName is used to take the database name
* prefix is used for attach the prefix to the generated ID.
* columnName is the name of the column of the table.
*/

import java.sql.ResultSet;
import java.sql.Statement;
import model.connection.connection;

/**
*
* @author Arnab
*/
public class IdGenerator
{
private String next_id;

public String getNextId(String tableName,String prefix,String columnName)
{
connection con=new connection(); //create the connection of database.
try
{
int temp=0;
Statement stmt=con.getCon().createStatement(); // getCon() is the return type of created Connection.
ResultSet rs=stmt.executeQuery("select "+columnName+" from "+tableName);
while(rs.next())
{
String t_code_temp=rs.getString(1).trim();
int code=Integer.parseInt(t_code_temp.substring(t_code_temp.indexOf(prefix)+prefix.length()));
if(code>temp)
{
temp=code;
}
}

next_id=prefix+(++temp);
}
catch(Exception e)
{
ExceptionLogger.writeToFile(this.getClass().getName()+": "+e); //This is the file where Exceptions are stored.
}
return next_id;
}