0

I am trying to generate random columns with the use of below method and after generating columns, I am using those columns in my SELECT sql.

final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + "  from " + table.getTableName() + " where id = ?";

/**
 * A simple method to get the column names in the order in which it was
 * inserted
 * 
 * @param columns
 * @return
 */
private String getColumns(final List<String> columns) {
    List<String> copy = new ArrayList<String>(columns);
    Collections.shuffle(copy);

    int rNumber = random.nextInt(columns.size());

    List<String> subList = copy.subList(0, rNumber);
    Collections.sort(subList, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
        }
    });
    return StringUtils.join(subList, ",");
}

Problem Statement:-

Sometimes I have seen is columnsList value is empty and if it is empty then selectSql will not work as there will be extra , before from keyword. How can I make sure getColumns should return atleast one entry everytime.

I believe nextInt will generate random number between 0 (inclusively) and n (exclusively). So it might be possible that it will pick 0 sometimes, Any way to generate random number between 1(inclusively) and n (exclusively)

AKIWEB
  • 19,008
  • 67
  • 180
  • 294

1 Answers1

1

One way is:

return subList.isEmpty() ? "1" : StringUtils.join(subList, ",");

But I think better is to modify selectSql to

final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE " + columnsList + "  from " + table.getTableName() + " where id = ?";

And then

return subList.isEmpty() ? "" : ","+StringUtils.join(subList, ",");

If you want at leas one value from random you can also use this:

int rNumber = 1+random.nextInt(columns.size()-1);
valodzka
  • 5,535
  • 4
  • 39
  • 50
  • Thanks valodzka. After editing like this, I am getting this exception sometimes `java.sql.SQLException: Column '' not found in results.` Do you know why it is happening? – AKIWEB Mar 01 '13 at 20:20
  • What other code should I provide here? I tried your other way as well which is giving me some other exception. – AKIWEB Mar 01 '13 at 20:25
  • What kind of error you get when using "int rNumber = 1+random.nextInt(columns.size()-1);"? – valodzka Mar 01 '13 at 20:44