如何在Android Sqlite中使用WHERE IN子句?

时间:2014-10-30 05:23:32

标签: android sqlite

我正在尝试执行单个更新查询,我必须为许多人更新单个字段。 现在,以下查询有效: -

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

一起使用时,它不会返回更新的行数

我正在尝试使用返回no的update方法来形成此查询。受影响的行

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

但这不起作用。

4 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();
    }
}

希望这有帮助。

答案 2 :(得分:0)

试试这段代码。

在您的IN数据中加上单引号

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

答案 3 :(得分:0)

我没试过这个..试试看......让我知道它是否有效..

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