2012-05-27 40 views
4

我調用SQLiteDatabase.query並獲得一個Cursor。雖然我還在遍歷該遊標,但是可以安全地從同一個線程發出其他查詢嗎?執行新的SQLite查詢是否安全,同時仍在迭代遊標以查詢以前的查詢? (Android)

+0

我認爲你接受的答案是不正確。請參閱下面我的答案中的示例代碼。 – ditkin

+0

在執行這兩個光標將不會在同一時間得到執行,outter光標正在運行時,內部光標將在等待位置和副版本@Travis – Lucifer

+0

我試圖ditkin的代碼和它的工作原理:第一個查詢不會失去自己的位置時,第二個查詢正在執行,這是我所擔心的(或者更糟糕的是,一個異常或死鎖)。我不確定你指的是什麼等待位置。只有一個線程,所以顯然不會有任何併發​​或後臺執行。 – Travis

回答

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); 
} 
+0

在後臺,兩個遊標只會一個接一個執行。 – Lucifer

+0

OP詢問是否可以安全地執行來自同一線程的其他查詢。它是。 – ditkin

+0

查詢並從同一個線程同時光標,請正確讀取它。 – Lucifer

3

No Two Query同時在同一個表上執行。它是內置的同步方法,因此一次只能執行一個查詢。您的第二個查詢將處於等待狀態,直到第一個完成執行。

+3

-1我認爲這個答案是錯誤的。您可以從同一個線程中獲得多個未完成的查詢並獨立訪問每個遊標。 – ditkin

+0

+1簡單和簡單的答案 –

+0

謝謝@BhavikAmbani – Lucifer