views:

254

answers:

1

How do I escape parameters of queries in JDO (Google App Engine)?

For example, how do I make the next snippet safe, if the variable name may contain unsafe chars as single quotes (')

PersistenceManager pm = ...;
String query = "select from Person where name='"+name+"'";
List<Shortened> shortened = (List<Shortened>) pm.newQuery(query).execute();
+4  A: 

Use query parameters instead, it's a much safer than including the values in the query itself. Here is an example from the GAE documentation:

Query query = pm.newQuery("select from Employee " +
                          "where lastName == lastNameParam " +
                          "order by hireDate desc " +
                          "parameters String lastNameParam");

List<Employee> results = (List<Employee>) query.execute("Smith");
Todd Owen
+1 bazillion. I wish there was some way to make a computer explode if you try to use string substitution on a query.
Nick Johnson
Sadly, the GAE documentation examples use String query = "..." style, at least the pages I found do.Having trouble finding where to import Query from, but I haven't looked much, yet; I'll get it! :)
Olie
Btw, it's: import javax.jdo.Query;For the next guy looking. Duh. ;)
Olie