java方法中返回String[],String[].length不正确

标签 java

我想要的是将数据插入数组 String[] 中,然后打印数组值。 返回String[]类型的方法是

public String[] getRequirementDocIDofProject(String testprojectName)
        throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    String req_doc_ids[] = null;
    String str_sqlQuery = "select * from req_specs INNER JOIN nodes_hierarchy nh " + 
            "on nh.id=req_specs.testproject_id  " + 
            "INNER JOIN requirements reqs " + 
            "on req_specs.id =reqs.srs_id where nh.name='" + testprojectName + "'";
    int count = 0;
    int n = 0;
    initDB();
    resultSet = statement.executeQuery(str_sqlQuery);
    while (resultSet.next()){
        count = Integer.parseInt(resultSet.getString(1));
    }
    req_doc_ids = new String[count];

    resultSet = statement.executeQuery(str_sqlQuery);
    while (resultSet.next()) {
        req_doc_ids[n] = resultSet.getString("req_doc_id");
        System.out.println("REQID=" + req_doc_ids[n]);
        n++;
    }
    close();
    System.out.println("n==" + n);
    return req_doc_ids;
}

调用方法代码为

DBConnection dbcon = new DBConnection();
String req_doc_ids[] = dbcon.getRequirementDocIDofProject("XXXX");
System.out.println(req_doc_ids.length);

控制台中的打印消息是
REQID=TECH-6104
REQID=TECH-6686
REQID=TECH-5391
REQID=TECH-5965
REQID=TECH-6530
REQID=TECH-6729
REQID=TECH-7082
REQID=TECH-7107
REQID=TECH-7184
n==9
7166

为什么 req_doc_ids.length 的值为 7166 而不是 9

最佳答案

7166 来自结果集的第 1 列 - 它是最后一行中的值。

while(resultSet.next()){
    count=Integer.parseInt(resultSet.getString(1));
}

相反,您的意思可能是:

while(resultSet.next()){
    count++;
}

请注意,这是一种不必要的低效创建数组的方法。使用 List 代替;或者,使用结果集API上的方法直接获取行数。

关于java方法中返回String[],String[].length不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53811629/

相关文章:

java - 如何使用 Java 创建音乐轨道的图形表示?

java - @Configuration 类中 @PostConstruct 的预期行为是什么?

java - 如何通过子类型避免kotlin工厂类方法?

java - 下面的: arrayName[x]++; work and what does it output in the following context?怎么办

javascript - 在原生 Android View 中渲染 React-Native 组件(UI 组件)

Java, IllegalAccessorError : superclass access check failed

java - 如何转换为指定的类类型?

java - hibernate ,获取重复值

java - 泛型集合 PECS

java - AWS Pinpoint - 如何在程序中设置推送通知