Вопрос

I'm building a MongoDB Java query, and while trying to find a specific value in my db, the query the query gets all messed up, because of some unwanted '\' chars in my String. Here is what I'm am doing.

I get a list of Strings from my mongodb, and then I perform a find in another collection, using those Strings.

DBCursor = null;
for(String s : list){
 BasicDBOject query = = new BasicDBObject("actor.preferredUsername",  s);
 cursor = coll.find(query);
 //treat the results
 }

If I do a System.out.println() using the query, this is what I get:

 { "actor.preferredUsername" : "\"NapoleSunset75\""}

Notice the '\' in the last field.

Now, for test purposes, if I change 's' to a fixed String like "xpto", the query is created in a sucessfully, returning

 { "actor.preferredUsername" : "xpto"}

Can anyone help?

Это было полезно?

Решение

I think, this is due to extra quote inside the string which is going to store in your database. If that's so you can use this class and It's static public method to validate your String before storing in your database :

public class SqlValidator {

private static final String SINGLE_QUOTE    = "\u0027";

    /**
     * It replaces all ' with ''. It should be used in read/write queries.
     * 
     * @param str
     */
    public static String quoteInQuery(String str) {
    if (str == null)
        return null;
    return str.replaceAll(SINGLE_QUOTE, SINGLE_QUOTE + SINGLE_QUOTE);
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top