我调用SQLiteDatabase.query并获取一个Cursor。虽然我仍在迭代该游标,但是从同一个线程发出其他查询是否安全?
答案 0 :(得分:3)
No Two Query同时在同一个表上执行。它是内置的同步方法,因此它一次只执行一个查询。您的第二个查询将处于等待位置,直到第一次完成其执行。
答案 1 :(得分:2)
是。您可以在同一个线程中拥有多个未完成的查询,并可以独立访问每个游标。
我将以下代码添加到测试活动中,并按预期运行:
SQLiteDatabase connection = getApplicationContext().openOrCreateDatabase("foo.db", MODE_PRIVATE, null);
try {
connection.execSQL("drop table if exists person");
connection.execSQL("create table person (id integer, name string)");
ContentValues cv = new ContentValues();
cv.put("id", 1);
cv.put("name", "leo");
connection.insert("person", null, cv);
cv = new ContentValues();
cv.put("id", 2);
cv.put("name", "yui");
connection.insert("person", null, cv);
Cursor rs = connection.query("person", new String[] {"id", "name" }, null, null, null, null, null);
while(rs.moveToNext())
{
System.out.println("name = " + rs.getString(1));
System.out.println("id = " + rs.getString(0));
Cursor rs2 = connection.query("person", new String[] {"id", "name" }, null, null, null, null, null);
while (rs2.moveToNext()) {
System.out.println("name = " + rs2.getString(1));
System.out.println("id = " + rs2.getString(0));
}
}
} catch (Exception e) {
System.out.println("Exception " + e);
}