将结果集的行存储在字符串数组中

时间:2013-07-10 16:30:34

标签: java sql jdbc

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

     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数组中。我使用了以下代码

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

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

例如,如果我在jTextField中输入优先级,结果集将包含 优先级为1 优先级2 priority3

3 个答案:

答案 0 :(得分:5)

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

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

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);
    }
}

答案 1 :(得分: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));


    }

答案 2 :(得分:0)

为什么不创建HashSet<String>并写入。请注意,HashSet是无序的,就像您的查询一样。通过使用任意大小的集合,您无需事先确定require dsize。