【问题标题】:Make sure I am getting one entry using Randomness确保我使用随机性获得一个条目
【发布时间】:2013-03-01 20:10:12
【问题描述】:

我正在尝试使用以下方法生成随机列,在生成列之后,我在 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, ",");
}

问题陈述:-

有时我看到columnsList 的值是空的,如果它是空的,那么selectSql 将不起作用,因为在from keyword 之前会有额外的,。我如何确保getColumns 每次都至少返回一个条目。

我相信nextInt 会在0 (inclusively) and n (exclusively) 之间生成随机数。所以它有时可能会选择0,任何方式在1(inclusively) and n (exclusively)之间生成随机数

【问题讨论】:

    标签: java random string-utils


    【解决方案1】:

    一种方法是:

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

    但我认为最好将selectSql修改为

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

    然后

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

    如果你想从随机中得到至少一个值,你也可以使用这个:

    int rNumber = 1+random.nextInt(columns.size()-1);
    

    【讨论】:

    • 谢谢瓦洛兹卡。像这样编辑后,我有时会收到这个异常java.sql.SQLException: Column '' not found in results.你知道为什么会这样吗?
    • 我应该在这里提供什么其他代码?我也尝试了你的其他方式,这给了我一些其他例外。
    • 使用“int rNumber = 1+random.nextInt(columns.size()-1);”时会出现什么样的错误?
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多