java - 问 : How to update 1 column with same data for different IDs (android)

标签 java android sqlite

这里我有一个 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/

相关文章:

java - 无法从sqlite数据库android中删除行

iPhone:使用 SQLite 制作简单的高分系统

java - 如何从自定义 Gmail 域发送邮件?

java - String replace() 和 replaceAll() 的区别

android - android应用程序如何与后端服务器同步数据?

android - 如何使用Gradle更改App Bundle的生成文件名?

android - 更改 fragment 内的抽屉导航项目

c - 为什么 sqlite 允许第二个进程进行写操作而第一个进程已经在进行写操作

java - JPA - 在模型中使用注解

java - 收到 OAuthException : An unexpected error has occurred. 类型的 Facebook 错误响应,请稍后重试您的请求。 (代码 2,子代码为空)