我想计算结果集中的条目数,然后将这些值存储在数组中并传递此数组以创建图形.
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.
Run Code Online (Sandbox Code Playgroud)
现在我想将结果集的值存储在一个字符串数组中.我使用了以下代码
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Run Code Online (Sandbox Code Playgroud)
错误:描述符索引无效.请建议如何在数组中复制resultset的结果.
例如,如果我在jTextField中输入优先级,则结果集将包含priority1 priority2 priority3
在你的第一个while循环中你读取了所有的条目ResultSet,所以当执行第二个while循环时,没有别的东西可以阅读.此外,索引ResultSet#getXxx从1开始,而不是从0开始.此外,由于您不知道将要读取的行数,因此最好使用List支持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));
}
Run Code Online (Sandbox Code Playgroud)
根据您的评论,我扩展了样本:
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);
}
}
Run Code Online (Sandbox Code Playgroud)