开发者

Android ormlite like() function is not working

I am new to this, please help me.

I am trying to use ormlite like(column name,value) function, but this is not working for me. But when I test full text it is working like "eq" function.

My Code is,

try {
    QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
    qb.where().like("madeCompany", filterKey);
    PreparedQuery<MakeDTO> pq = qb.prepare();
    return makeDao.query(pq);
} catch (SQLException e) {
  开发者_如何学运维  throw new AppException(e);
}

Thanks.


An old question, but something I just solved (ORMLite's documentation isn't that clear). you need to wrap your query parameter in "%"'s in order to tell ORMLite which side of your query string can match any number of characters.

For example, if you want your query to match any madeCompany that contains your string use the following:

try {
    QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
    qb.where().like("madeCompany", "%"+filterKey+"%");
    PreparedQuery<MakeDTO> pq = qb.prepare();
    return makeDao.query(pq);
} catch (SQLException e) {
    throw new AppException(e);
}


Pretty simple, you're asking it to be exactly the string 'madeCompany', if you want to do partial matching you need to use the % wildcard etc.

public Where<T,ID> like(java.lang.String columnName,
                        java.lang.Object value)
                 throws java.sql.SQLException
Add a LIKE clause so the column must mach the value using '%' patterns.
Throws:
java.sql.SQLException

Where.like(java.lang.String, java.lang.Object)


The answers above can resolved the like query problem, but has SQL injection risk. If the value of 'filterKey' is ', it will cause SQLException, because the SQL will be SELECT * FROM XXX WHERE xxx LIKE '%'%'. You could use SelectArg to avoid, example for this case:

try {
    String keyword = "%"+filterKey+"%";
    SelectArg selectArg = new SelectArg();
    QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
    qb.where().like("madeCompany", selectArg);
    PreparedQuery<MakeDTO> pq = qb.prepare();
    selectArg.setValue(keyword);
    return makeDao.query(pq);
} catch (SQLException e) {
    throw new AppException(e);
}

Reference: http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_3.html#index-select-arguments

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜