我想要的是将数据插入数组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
答案 0 :(得分:4)
7166来自结果集的第1列-它是最后一行中的值。
MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {currView: 'graph'};
}
handleToggle() {
if (this.state.currView === 'graph') {
this.setState({currView: 'otherView'});
} else {
this.setState({currView: 'graph'});
}
}
render() {
if(this.state.currView === 'graph') {
// render your 'graph' view
} else {
// render some other view
}
}
}
相反,您可能是说:
while(resultSet.next()){
count=Integer.parseInt(resultSet.getString(1));
}
请注意,这是创建数组的不必要的低效方式。请改用while(resultSet.next()){
count++;
}
;或者,使用结果集API上的方法直接获取行数。
答案 1 :(得分:1)
您的主要问题已经由安迪(Andy)弄清了,这个答案只是为了帮助您使用当前代码而进行的扩展。
可以在代码中进行改进。
更喜欢使用PreparedStatement而不是Statement
,这不安全,并且可能会受到Jon Skeet提到的SQL注入攻击的威胁。
为什么要运行两次数据库查询,而这可能只是为了找出正确初始化String数组的记录数而可能是一个繁重的查询。
使用List<String>
存储获得的任意数量的行,最后将列表转换为数组,如下面的代码所示。
摆脱很多不必要的变量和太多行代码,使您的代码清晰明了。
您可以尝试将方法更改为此,
public String[] getRequirementDocIDofProject(String testprojectName)
throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
List<String> reqDocIdList = new ArrayList<String>();
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 + "'";
initDB();
resultSet = statement.executeQuery(str_sqlQuery);
while (resultSet.next()){
System.out.println("REQID=" + resultSet.getString("req_doc_id"));
reqDocIdList.add(resultSet.getString("req_doc_id"));
}
close();
System.out.println("n==" + reqDocIdList.size());
return reqDocIdList.toArray(new String[reqDocIdList.size()]);
}