appengine datastore query escaping single quote(')

时间:2012-03-04 03:28:32

标签: java sql google-app-engine jdo

我使用过像JDO for Google App Engine: escaping quotes这样的javax.jdo.Query。然而,我的单引号(')查询字符串不断爆炸。

Query query = pm.newQuery("select from " + Book.class.getName() + " where mArtist== '"+ artist + "' &&  mTitle=='" + title + "'");

这是例外

javax.jdo.JDOUserException: Portion of expression could not be parsed: 't Give Up' 
org.datanucleus.store.query.QueryCompilerSyntaxException: Portion of expression could not be parsed: 't Give Up'

这是query.toString()

SELECT FROM com.example.Book WHERE mArtist== 'Famous Writer' &&  mTitle=='We Won''t Give Up'

是的,我甚至通过每个appengine docs双单引号逃脱单引号(')

a str literal, as a single-quoted string. Single-quote characters in the string must be escaped as ''. For example: 'Joe''s Diner'

2 个答案:

答案 0 :(得分:2)

通过字符串连接构建查询几乎总是一件危险的事情,即使无法进行SQL注入攻击也是如此。 (他们没有GAE。)

请参阅http://code.google.com/appengine/docs/java/datastore/jdo/queries.html#Introducing_Queries并注意“参数替换”。

答案 1 :(得分:1)

文档中的示例代码仅涵盖单个参数替换。这里还有一点。

Query query = pm.newQuery(Book.class);
query.setFilter("mArtist == artist && mTitle == title");
query.declareParameters("String artist,String title");              
List<Book> list = (List<Book>) query.execute("Famous Writer","We Won't Give Up");

有些值得一读的问题:

How to dynamically build JDO Queries on multiple parameters

Google Datastore problem with query on *User* type