正如标题清楚描述的那样,我们resultset.hasNext()
意外地返回false
。
这是我的基于Jena的SPARQL查询和Java源代码:
SELECT ?s ?label WHERE { ?s rdfs:label ?label. FILTER(CONTAINS(LCASE(?label), "university"@en)). } LIMIT 5
Query query = QueryFactory.create(PREFIX + sparqlQuery);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService("https://query.wikidata.org/sparql", PREFIX + sparqlQuery);
try {
ResultSet results = queryExecution.execSelect();
ResultSetFormatter.out(System.out, results, query);
while (results.hasNext()) { // returns false
QuerySolution querySolution = results.next();
System.out.println(querySolution.getResource("s"));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
} finally {
queryExecution.close();
}
以下是输出:
------------------------------------------------------
| s | label |
======================================================
| wd:Q1060 | "Technical University of Hamburg"@en |
| wd:Q1060 | "Technical University of Hamburg"@en-ca |
| wd:Q1060 | "Technical University of Hamburg"@en-gb |
| wd:Q1060 | "Technical University of Hamburg"@nl |
| wd:Q4027 | "Jean Moulin University Lyon 3"@en |
------------------------------------------------------
答案 0 :(得分:6)
您只能在Resultset
上进行一次迭代,这已在便捷方法ResultSetFormatter.out(...)
我不知道您是否真的需要处理ResultSet
两次,但如果是这样,您可以创建一个允许重置光标的ResultSetRewindable
:
Query query = QueryFactory.create(PREFIX + sparqlQuery);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService("https://query.wikidata.org/sparql", PREFIX + sparqlQuery);
try {
ResultSet rs = queryExecution.execSelect();
ResultSetRewindable results = ResultSetFactory.copyResults(rs);
ResultSetFormatter.out(System.out, results, query);
results.reset();
while (results.hasNext()) { // returns false
QuerySolution querySolution = results.next();
System.out.println(querySolution.getResource("s"));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
} finally {
queryExecution.close();
}