gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:44:51 24 4
gpt4 key购买 nike

我想要的是将数据插入数组 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com