2015-06-25 24 views
0

我有一个表在我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. 

所有这些例子都将工作到一定的程度,但它们都有缺陷。不知怎的,我觉得我错过了解决方案,因此,问题:

执行此类查询的正确方法是什么?

谢谢。

+0

插入'idList'到一些临时表,并加入... – Selvin

+1

也'COL_ID = 1 OR COL_ID = 2 ... OR COL_ID = n'可以简单地写成COL_ID IN(1,2,...,n)' – Selvin

+1

我同意laalto的答案,但我预测当你测量你的程序时,你会发现 * * 1。**没有任何*明显*开销。 (围绕所有查询使用单个事务。) –

回答

1

对于问题中的特殊情况,请考虑WHERE id IN (x,y,z, ...)

为了解决在标题的问题,而不只是特殊情况下,在问题正文:

Android的SQLite的API是不是在这方面非常灵活。

在原sqlite3的C API人会用一个sqlite3_prepare*()调用做到这一点获得sqlite3_statement和地点绑定的参数,sqlite3_step()让行(S),然后重新设置语句新的参数绑定重用。

在Android API中,该语句对应于Cursor,步进等同于移动光标。重置和重新绑定功能仅在SQLiteCursor中可用,如requery()setSelectionArguments()

所以尝试一些大意如下:

  1. 做常规查询与选择ARGS。

  2. 假设默认光标工厂,将结果Cursor投射到SQLiteCursor

  3. 访问行()你所需要的。

  4. 更新的选择ARGS与setSelectionArgs()

  5. requery()

  6. 转到3除非做

相关问题