我想执行一个sqlite查询:
c = db.rawQuery("SELECT " + KEY_BOOK_ID+ " , " + KEY_BOOK_CODE + " , " + KEY_ISBN + " , " +
KEY_VOL_NO + " , " + KEY_BRAND + " , " + KEY_SKU + " , " + KEY_TITLE +
" , " + KEY_PRICE + " , " + KEY_LANG + " , " + KEY_STATUS + " FROM " +
BOOKS_TABLE + " WHERE " + KEY_SKU + " IN " + inClause + ";", null);
in子句中的值需要从字符串数组中获取:
String values[] = {"Singles","5 in 1 series","Childrens Book"};
以下是我的错误日志。
引起:android.database.sqlite.SQLiteException:near" 1": 语法错误(代码1):,编译时:SELECT book_id,book_code, ISBN,vol_no,品牌,sku,标题,价格,lang,状态FROM books_table WHERE sku IN(单打,5合1系列,儿童读物); 在 android.database.sqlite.SQLiteConnection.nativePrepareStatement(母语 方法) 在 android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1112) 在 android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:689) 在 android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 在android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:58) 在android.database.sqlite.SQLiteQuery。(SQLiteQuery.java:37) 在 android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44) 在 android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1433) 在 android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1372)
这是我调用以获取Json对象的方法。
public JSONObject searchForBooks( )
{
String values[] = {"Singles","5 in 1 series","Childrens Book"};
String inClause = Arrays.toString(values);
//replace the brackets with parentheses
inClause = inClause.replace("[","(");
inClause = inClause.replace("]",")");
SQLiteDatabase db = this.getReadableDatabase();
Cursor c ;
c = db.rawQuery("SELECT " +KEY_BOOK_ID+ " , " + KEY_BOOK_CODE + " , " + KEY_ISBN +
" , " + KEY_VOL_NO + " , " + KEY_BRAND + " , " + KEY_SKU + " , " +
KEY_TITLE + " , " + KEY_PRICE+ " , " + KEY_LANG+ " , " + KEY_STATUS
+ " FROM " + BOOKS_TABLE + " WHERE " + KEY_SKU + " IN " + inClause + ";",
null);
if (c.moveToFirst()) {
do {
JSONObject jobj = new JSONObject();
try {
jobj.put("book_id", c.getString(0));
jobj.put("book_code", c.getString(1));
jobj.put("ISBN", c.getString(2));
jobj.put("vol_no", c.getString(3));
jobj.put("brand", c.getString(4));
jobj.put("sku", c.getString(5));
jobj.put("title", c.getString(6));
jobj.put("price", c.getString(7));
jobj.put("lang", c.getString(8));
jobj.put("status", c.getString(9));
jarr1.put(0, jobj);
jm1.put("books_info", jarr1);
Log.d("Selected BOOKS info", jm1.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} while (c.moveToNext());
}
c.close();
db.close();
return jm1;
}
感谢任何帮助或建议。谢谢。
答案 0 :(得分:2)
你错过了这些字符串的引号。
我会以稍微不同的方式构建in子句
page_load
修改强>
要避免什么CL。在他的评论中描述,你可以替换
String values[] = {"Singles","5 in 1 series","Childrens Book"};
boolean first = true;
String inClause = "(";
for(String v : values){
if(first){
first = false;
} else {
inClause += ","
}
inClause += "'" + v + "'";
}
inClause += ")";
与
inClause += "'" + v.replaceAll("'", "''") + "'";
这样一来,如果你的字符串中有单引号,它们将被转义,不会弄乱最终的查询。