简体   繁体   中英

How to add a string variable to the SPARQL query?

I want to integrate the user's input into a SPARQL query. Here's my existing code but I cannot get it to work.

public void setName(String name) {
    String formattedName = name.replace(" ", "-");
    String query = "SELECT ?p ?o WHERE { <http://person/" + formattedName + "> ?p ?o }" ;
    System.out.println(query);
    QueryExecution qe = QueryExecutionFactory.sparqlService(
            "http://localhost:3030/Date/query", 
            "PREFIX dc: <http://purl.org/dc/elements/1.1/> " + query);
    ResultSet results = qe.execSelect();
    System.out.println(results);
    qe.close();
}

Then I get the following output in the console:

SELECT ?p ?o WHERE { <http://person/Mark-John> ?p ?o }
com.hp.hpl.jena.sparql.resultset.XMLInputStAX$ResultSetStAX@28df8261

The first line is the query and the second line is the result, which should be the data received...

It works if I try as follows:

execSelectAndPrint(
        "http://localhost:3030/Date/query",
        "PREFIX dc: <http://purl.org/dc/elements/1.1/> " + "SELECT ?p ?o WHERE { <http://person/Mark-John> ?p ?o }"
        );

Which prints:

| <http://purl.org/dc/elements/1.1/name>        | "Mark John" |
| <http://purl.org/dc/elements/1.1/nationality> | "American"  |

How can I change my first code to display the results from the second one?

The title of your question has nothing to do with the problem that you describe in the text...

You're more asking "How to print the Apache Jena API ResultSet ?"

And then it's confusing that you already have one method called execSelectAndPrint that does what you want. So the question is why can't you (re)use that method or at least the corresponding lines of codes in the method?

Apache Jena API documentation, in particular the part with SPARQL can be found here

ResultSet is an iterator, thus iterate over it:

ResultSet results = qexec.execSelect();
for ( ; results.hasNext() ; ) {
   QuerySolution qs = results.next() ;
   ...                                   // extract the variables
}

Or use one of the convenience methods :

ResultSet results = qexec.execSelect();
ResultSetFormatter.out(results);
Minor comment:

Your method is called setName which looks a bit strange wrt to what you're doing in this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM