3

我想计算结果集中的条目数,然后将这些值存储在一个数组中并传递这个数组来创建一个图形。

     ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as 
     call from tablename"); // this statement will select the unique entries in a 
                              particular column provided by jtextfield

     int count=0;

     while(rs.next())
       { ++count; } // This will count the number of entries in the result set.

现在我想将结果集的值存储在一个字符串数组中。我使用了以下代码

    String[] row = new String[count];
    while(rs.next())
     {
       for (int i=0; i <columnCount ; i++)
        {
          row[i] = rs.getString(i + 1);
        }
     }

错误:无效的描述符索引。请建议如何将结果集的结果复制到数组中。

例如,如果我在 jTextField 输入优先级,结果集将包含 priority1 priority2 priority3

4

3 回答 3

6

在您的第一个while循环中,您读取了 中的所有条目ResultSet,因此在执行第二个while循环时没有其他内容可读取。此外,索引ResultSet#getXxx从 1 开始,而不是从 0。此外,由于您不知道要读取的行数,因此最好使用Listbacked by ArrayList

考虑到这些,您的代码应如下所示:

ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
    " as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
    results.add(rs.getString(1));
}

根据您的评论,我扩展了示例:

public List<String> yourRandomQuery(String columnName) {
    Connection con = null;
    ResultSet rs = null;
    List<String> results = new ArrayList<String>();
    try {
        String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
        con = ...; //retrieve your connection
        ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
        while(rs.next()) {
            results.add(rs.getString(1));
        }
    } catch (SQLException e) {
        //handle your exception
        e.printStacktrace(System.out);
    } finally {
        closeResource(rs);
        closeResource(con);
    }
    return results;
}

//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
    try {
        if (ac != null) {
            ac.close();
        }
    } catch (Exception e) {
        //handle this exception as well...
    }
}

public void someMethod() {
    //retrieve the results from database
    List<String> results = yourRandomQuery(jTextField.getText());
    //consume the results as you wish
    //basic example: printing them in the console
    for(String result : results) {
        System.out.println(result);
    }
}
于 2013-07-10T16:38:09.843 回答
1

尝试这个

ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
            call from tablename");      
    List<String> list=new ArrayList<>();

    while(rs.next())
    {
       list.add(rs.getString(1));


    }
于 2013-07-10T16:37:39.953 回答
0

为什么不直接创建一个HashSet<String>并写入它。请注意,这HashSet是无序的,就像您的查询一样。通过使用任意大小的集合,您无需提前确定所需的 dsize。

于 2013-07-10T16:34:28.547 回答