这里我有一个 ID 数组,并且更新方法仅在数组中包含 1 个 ID 时才有效,但如果我放入 2-3 个 ID,则会出现错误......类似于:绑定(bind)参数太多。提供了 4 个参数,但该语句需要 2 个参数
我怎样才能使它工作。我想在同一列中为不同的 ID 设置相同的值。
ContentValues values = new ContentValues();
values.put(DataEntry.COLUMN_DATA, "1");
String selection = DataEntry._ID + "=?";
String[] selectionArgs = selectedData.toArray(new String[selectedData.size()]);
// To be a bit more clear the above line looks like this:
// String[] selectionArgs = { 1, 2, 3, 4, 5 }; String array of IDs which varies
int rowsAffected = getContentResolver().update(DataEntry.CONTENT_URI, values, selection, selectionArgs);
更新方法如下:
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int rowsUpdated = db.update(DataEntry.TABLE_NAME, values, selection, selectionArgs);
最佳答案
我相信你可以使用:-
ContentValues values = new ContentValues();
values.put(DataEntry.COLUMN_DATA, "1");
String selection = DataEntry._ID + "=?";
String[] selectionArgs = selectedData.toArray(new String[selectedData.size()]);
for each(String s: selectionArgs) {
int rowsAffected = getContentResolver().update(DataEntry.CONTENT_URI, values, selection, new String[]{s});
}
或者,您可以使用 WHERE IN(id 列表)
,其格式如下:-
ContentValues values = new ContentValues();
values.put(DataEntry.COLUMN_DATA, "1");
String selection " IN (?)";
String[] selectionArgs = selectedData.toArray(new String[selectedData.size()]);
StringBuilder sb = new StringBuilder();
for (int i=0; i < selectionArgs.length(); i++) {
sb.append(selectionArgs[i]);
if (i < (selectionArgs.length - 1)) {
sb.append(",");
}
}
int rowsAffected = getContentResolver().update(DataEntry.CONTENT_URI, values, selection, new String[]{sb.toString()});
当然,您可以循环应用 x 占位符。这将类似于:-
ContentValues values = new ContentValues();
values.put(DataEntry.COLUMN_DATA, "1");
String[] selectionArgs = selectedData.toArray(new String[selectedData.size()]);
StringBuilder sb = new StringBuilder("IN (");
for (int i=0; i < selectionArgs.length(); i++) {
if (i < (selectionArgs.length() - 1) {
sb.append("?,");
} else {
sb.append("?)");
}
}
int rowsAffected = getContentResolver().update(DataEntry.CONTENT_URI, values, sb.toString, selectionArgs);
- 请注意,这是原则上的代码,尚未经过测试,因此可能包含一些错误。
关于java - 问 : How to update 1 column with same data for different IDs (android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51030757/