【问题标题】:Fill array list with object of String[] with SQL table用 SQL 表用 String[] 的对象填充数组列表
【发布时间】:2015-10-29 08:28:17
【问题描述】:

我目前正在尝试使用带有 SQL 表的 String[] 对象填充数组列表。我能够使用此代码获取表的标题。

            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            int i = 1;
            while (colCount >= i) {
                String header = rsmd.getColumnName(i);
                field.add(header);
                i++;

但是,当我尝试创建行来填充表格时,数组不会添加到数组列表中。

            while (rs.next()) {
                String[] row = new String[colCount];
                for (int j = 0; j <= colCount; j++) {
                    row[j] = rs.getString(j+1);
                }
                data.add(row);
            }
        } catch (SQLException ex) {

        }
        System.out.println(data.size());

由于某种原因,当我放入“data.add(row);”时for 循环中的语句,它只显示同一行,但它循环了多少次。但它在 for 之外不起作用(我想将它放在 while 内的 for 循环之后)。我将列表的大小输出到控制台,它只返回 0。

【问题讨论】:

  • 您将忽略任何 SQLException 并继续,就好像没有发生任何重要的事情一样。这个不对。你确定没有人被扔吗?在catch 块内添加throw new RuntimeException(ex); 以确保。它必须停止程序并在控制台中打印问题的答案(异常消息和堆栈跟踪)。

标签: java mysql arrays jdbc


【解决方案1】:
String[] row = new String[colCount];
for (int j = 0; j <= colCount; j++) {
    row[j] = rs.getString(j+1);
}
            data.add(row);

亲爱的朋友们,为什么你决定写“j

如您所知,您尝试捕获 SQLException 但您什么也没做。因此,当结果集的第一行和 j = colCount + 1 时,您的代码已失败。它无法添加任何内容。

【讨论】:

  • 非常感谢!我最终修复了索引,它工作正常。
猜你喜欢
  • 2019-01-15
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多