我的 SQLite
数据库中有一个表:
物种:
_id | species | description
---------------------------
1 | Aardvark | Some description for Aardvark
2 | Aardwolf | Some description for Aardwolf
3 | Caracal | Some description for Caracal
我从服务器收到一个 ID 列表,我只想显示与我收到的 ID 相对应的物种。
现在我知道了一些选择:
1。这样做的明显而幼稚的方法是:
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();
}
这将执行太多的操作,并且我假设多个小的“磁盘”读取,这会非常慢。
2。另一种选择是使用 SQLiteStatement但这只返回一个值,这对我的示例和 shouldn't really be used for queries 不起作用无论如何。
3。另一种选择是手动将条件连接到原始 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.
所有这些示例都在一定程度上有效,但它们都有缺陷。不知何故,我觉得我缺少解决方案,因此问题是:
执行此类查询的正确方法是什么?
谢谢。
最佳答案
对于问题中的特殊情况,只需考虑WHERE id IN (x,y,z, ...)
。
要解决标题中的问题,而不仅仅是问题正文中的特殊情况:
Android SQLite API 在这方面并不是很通用。
在原始 sqlite3 C API 中,可以通过单个 sqlite3_prepare*()
调用来获取 sqlite3_statement
并将参数绑定(bind)到位,sqlite3_step( )
获取行,然后重置语句以将其与新参数绑定(bind)一起重用。
在Android API中,该语句对应于一个Cursor
,步进相当于移动光标。重置和重新绑定(bind)功能仅在 SQLiteCursor
中可用。如requery()
和setSelectionArguments()
。
因此尝试按照以下方式进行操作:
使用选择参数执行常规查询。
假设使用默认游标工厂,将生成的
Cursor
转换为SQLiteCursor
。访问您需要的行。
使用
setSelectionArgs() 更新选择参数
requery()
除非完成,否则转到 3
关于java - Android SQLite : Running the Same Query with Different Parameters Multiple Times Efficiently,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31050657/