ORCentral

src/eu/coform/database/command/NextIdCommand.java

Go to the documentation of this file.
00001 package eu.coform.database.command;
00002 
00003 import java.sql.ResultSet;
00004 import java.sql.SQLException;
00005 
00006 import eu.coform.database.DBException;
00007 import eu.coform.database.Database;
00008 import eu.coform.database.Query;
00009 import eu.coform.database.DBException.Error;
00010 
00014 public class NextIdCommand implements ResultDatabaseCommand {
00015 
00016    private Integer m_result;
00017    private String m_columnName;
00018    private String m_tableName;
00019 
00020    public NextIdCommand(String columnName, String tableName) {
00021       m_columnName = columnName;
00022       m_tableName = tableName;
00023    }
00024    
00025    @Override
00026    public Integer getResult() {
00027       return m_result;
00028    }
00029 
00035    @Override
00036    public void exec() throws DBException {
00037       Query query = Database.getInstance().getNewQuery();
00038 
00039       // Could also rely on auto-incremenet but
00040       // a) autoinc is evil
00041       // b) we'd need to query for the ID eitherway (at least after insert)
00042       query.setQuery("SELECT MAX(" + m_columnName + ") maxID FROM " + m_tableName + ";");
00043       ResultSet rs = Database.getInstance().query(query);
00044 
00045       try {
00046          if (!(rs.isBeforeFirst() && rs.isAfterLast())) {
00047             rs.next();
00048             m_result = new Integer(rs.getInt("maxID") + 1);
00049          }
00050          else
00051             // No entries found: start with zero
00052             m_result = new Integer(0);
00053       } catch (SQLException e) {
00054          e.printStackTrace();
00055          throw new DBException(Error.QueryInvalid);
00056       }
00057    }
00058 
00059 }
 All Classes Namespaces Files Functions Variables Enumerations