我有一个表在我SQLite
数据库:的Android的SQLite:运行使用不同的参数相同的查询多次有效地
种:
_id | species | description
---------------------------
1 | Aardvark | Some description for Aardvark
2 | Aardwolf | Some description for Aardwolf
3 | Caracal | Some description for Caracal
我收到ID列表从服务器我只想显示与我收到的ID相对应的物种。
现在我所知道的几个选项:
。这样做的明显的和幼稚的方法是沿着线的东西:
SQLiteDatabase db = this.openDatabase();
for (int id : idList) {
Cursor cursorSpecies = db.query(true, TABLE_SPECIES, new String[] {COL_SPECIES_SPECIES},
COL_ID + "=?", id, null, null, null, null);
cursorSpecies.moveToNext();
speciesList.add(cursorSpecies.getString(0));
cursorSpecies.close();
}
这将执行太多的操作,我以为多发小“盘”读,这将是非常缓慢的。
。另一种选择是使用SQLiteStatement,但这只返回一个值,这对我的示例和shouldn't really be used for queries无效。
。另一个选择是手动拼接的条件为原料SQL
查询,东西线沿线的:
SQLiteDatabase db = this.openDatabase();
String query = "SELECT * FROM " + TABLE_SPECIES + " WHERE ";
for (int id : idList) {
query += COL_ID + "=" + id + " OR ";
}
// I am aware this will end in an " OR" but this is not the point of this example so please ignore it.
Cursor cursorSpecies = db.rawQuery(query, null);
// Use the cursor and close it.
While this should work decently well, a very large query would probably break some query string length limit so this is not ideal either.
所有这些例子都将工作到一定的程度,但它们都有缺陷。不知怎的,我觉得我错过了解决方案,因此,问题:
执行此类查询的正确方法是什么?
谢谢。
插入'idList'到一些临时表,并加入... – Selvin
也'COL_ID = 1 OR COL_ID = 2 ... OR COL_ID = n'可以简单地写成COL_ID IN(1,2,...,n)' – Selvin
我同意laalto的答案,但我预测当你测量你的程序时,你会发现 * * 1。**没有任何*明显*开销。 (围绕所有查询使用单个事务。) –