5

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();
flybywire
  • 261,858
  • 191
  • 397
  • 503
  • I have a bit of more code and references here http://stackoverflow.com/questions/9552064/appengine-datastore-query-escaping-single-quote/9552818#9552818 – Win Myo Htet Mar 04 '12 at 06:21

1 Answers1

11

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
  • 15,650
  • 7
  • 54
  • 52
  • +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 Sep 30 '09 at 12:00
  • 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 Aug 05 '10 at 04:04
  • 1
    Btw, it's: import javax.jdo.Query; For the next guy looking. Duh. ;) – Olie Aug 05 '10 at 04:07