2014-10-30 61 views
0

我想執行一個更新查詢,我必須更新許多人的單個字段。 現在下面的查詢工作: -如何在Android Sqlite中使用WHERE IN子句?

UPDATE PERSON SET ISSELECTED=1 WHERE ID IN (132,142,115,141,41,133,40,56,139,134,135,65,143,9,64,39,120,104,122,35,19,98,124,127,130,136,119,123,55,102,5,128,140,95,138,131,96,93,129,103,94,89,126,21,29,125,3,101,92,113,4,88,111,63,60,38,114,90,31,118,99,121,117,100,112,97,25,116,10,32,27,30,14,26,12,61,57,20,107,110,91,109,108,106,105,16,62,33,59,18,58,36,11,15,37,28,24,6,7,8,34,13) 

但隨着execSqlrawQuery

我試圖形成使用update方法,它返回該查詢中使用時,它不會返回更新行數沒有。受影響的行數

int rowsUpdatedSelected = db.update("PERSON", values, "ID" + " = ?", new String[] {id.toString()}); 
// where id is a StringBuilder object containing the ids like above 

但這不起作用。

+0

是ID數字字段或數據庫中的文本 – 2014-10-30 05:26:44

+0

這是文本字段,但我在sqlite管理器中運行此查詢並更新了數據 – 2014-10-30 05:27:48

+0

您的查詢結束爲'... WHERE ID ='132,142,115,...''。 – 2014-10-30 10:05:51

回答

0

您可以嘗試使用sqlite3_changes()此:

該函數返回了對 改變或 插入或刪除由最近完成的SQL語句,由第一指定的數據庫連接數據庫的行數參數。對僅由INSERT,UPDATE或DELETE語句 指定的更改 進行計數。

所以您的更新語句後,添加以下代碼:

Cursor cursor = null; 
try 
{ 
    cursor = db.rawQuery("SELECT changes() AS updated_row_count", null); 
    if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) 
    { 
     final long count = cursor.getLong(0); 
     Log.d("LOG", "no. of updated rows : " + count); 
    } 
} catch(SQLException e) 
{ 
    e.printStackTrace(); 
} finally 
{ 
    if(cursor != null) 
    { 
     cursor.close(); 
    } 
} 

希望這有助於。

+0

這是低效的,因爲我需要更新行並且更新方法返回行數並且查詢正常。我只需要根據SQLiteDatabase的'update'方法來修改它。 – 2014-10-30 05:31:37

2

您可以編寫一個方法來創建IN查詢字符串並將其用作selectionArgs。像下面

selectionArgs = idArray; // Where id array will be String[] and will contain all of your ids 
selection = "ID" + makeInQueryString(idArray.length); 

哪裏makeInQueryString()

/** 
* Creates where string which can be used for IN query. It creates string 
* containing "?" separated by ",". This method can be used as below <br> 
* ColumnName + makeInQueryString(size) <br> 
* This will create IN query for provided column name. 
* 
* @param size 
*   size of the items 
* @return IN query string of the form (?,?,?,?) 
*/ 
public static String makeInQueryString(int size) { 
    StringBuilder sb = new StringBuilder(); 
    if (size > 0) { 
     sb.append(" IN ("); 
     String placeHolder = ""; 
     for (int i = 0; i < size; i++) { 
      sb.append(placeHolder); 
      sb.append("?"); 
      placeHolder = ","; 
     } 
     sb.append(")"); 
    } 
    return sb.toString(); 
} 
0

試試這個代碼。

把單引號對你在你的數據

UPDATE PERSON SET ISSELECTED=1 WHERE ID IN ('132','142','115','14','1'); 
+0

我想使用數據庫的UPDATE方法。原始查詢很好,正在執行 – 2014-10-30 05:33:33

0

我沒有嘗試這個..只是給一個嘗試..讓我知道wethr其工作或不..

int rowsUpdatedSelected = db.update("PERSON", values, "ID IN (?)", new String[] {id.toString()}); 
相關問題