Worked example — a parameterised SELECT.
You write the query with a variable where the dynamic value will go. The application supplies the value at call time:
# Your query template (saved as a string, no concatenation):
PREFIX : <http://example.org/>
SELECT ?book WHERE {
?book :author ?author .
}
# Python (rdflib) — the library binds ?author for you:
from rdflib import Literal
from rdflib.plugins.sparql import prepareQuery
q = prepareQuery(QUERY_STRING)
results = graph.query(q, initBindings={'author': Literal('Alice')})
What the library does for you:
- Quotes & escapes the value.
- Tags it with the right datatype (here
xsd:string).
- Substitutes it into the query as a typed RDF term.
Same query template, different bindings each call — the SemWeb equivalent of a SQL prepared statement. Below, write just the SPARQL template; the grader assumes ?author is bound by the host application.