如何为此查询编写预准备语句?

时间:2018-05-14 09:17:22

标签: java android sqlite prepared-statement

您好我已经为我的应用及其工作编写了一个连接查询。我的下一个要求是将该查询转换为准备好的语句,我被困住了。

"SELECT * FROM " + TableA.TABLE + " as d LEFT JOIN " + TableB.TABLE + " as c ON d."+ TableA.DAMAGECODE + "=c." + TableB.DAMAGECODE + " AND d."
+ TableA.INDEX + "=c." + TableB.DAMAGECODEINDEX + " AND d."
+ TableA.OBJECTTYPE + "=c." + TableB.OBJECTCLASS + " WHERE d."+ TableA.LEAF + " = '1' AND d." + TableA.OBJECTTYPE + " = ? AND " + "(d."+ TableA.DAMAGECODE + " LIKE ? OR d." + TableA.DAMAGETEXT + " LIKE ?) AND c." + TableB.CONSTRUCTIONSERIES + " = ? ORDER BY " + TableA.DAMAGETEXT;

cursor = db.rawQuery(sql,new String[]{String.valueOf(objectClass),"'%" + query + "%'","'%" + query + "%'",constructionSeries});

当我运行原始查询时,我得到了结果,但是当运行上面准备好的语句时,我的光标数总是为零

1 个答案:

答案 0 :(得分:1)

传递'参数时,您无需自己添加StringPreparedStatement将自行管理这些参数。

"'%" + query + "%'"

目前你有条件

where columnA = "'%somethingToFind%'"

所以,除非你的columnA中的值类似'somethingToFindInColumnA'(请注意String的开头和结尾的引号)。你永远不会得到结果。

删除它们以获得类似:

"%" + query + "%"

完整答案:

db.rawQuery(sql,new String[]{String.valueOf(objectClass),"'%" + query + "%'","'%" + query + "%'",constructionSeries});

成为:

db.rawQuery(sql,new String[]{String.valueOf(objectClass),"%" + query + "%","%" + query + "%",constructionSeries});