更新单行数据

本文介绍如何通过 Java SDK 更新表格存储数据表中的单行数据,您可以更新属性列的值、添加属性列、删除属性列的某个版本或整个属性列。

前提条件

初始化Tablestore Client

方法说明

public UpdateRowResponse updateRow(UpdateRowRequest updateRowRequest) throws TableStoreException, ClientException

UpdateRowRequest参数说明

  • rowChange(必选)RowUpdateChange:更新的行数据信息,包含以下参数。

    名称

    类型

    说明

    tableName(必选)

    String

    数据表名称。

    primaryKey(必选)

    PrimaryKey

    主键信息,包括主键列名称和主键值。

    • 主键列数据类型包括 STRING、INTEGER 和 BINARY。

    • 主键个数和类型必须与数据表的主键保持一致。

    columnsToUpdate(必选)

    List<Pair<Column, Type>>

    更新的属性列信息和操作类型。

    condition(可选)

    Condition

    写入条件,详情请参见条件更新

示例代码

以下示例代码用于修改 test_table 表中主键值为 row1 的行数据,将属性列 col1 的值修改为 changed_val1。

public static void updateRowExample(SyncClient client) {
    // 构造主键
    PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
    PrimaryKey primaryKey = primaryKeyBuilder.build();

    // 构造更新行数据
    RowUpdateChange rowUpdateChange = new RowUpdateChange("test_table", primaryKey);
    rowUpdateChange.put("col1", ColumnValue.fromString("changed_val1"));

    // 调用 updateRow 方法更新行数据
    UpdateRowRequest updateRowRequest = new UpdateRowRequest(rowUpdateChange);
    UpdateRowResponse updateRowResponse = client.updateRow(updateRowRequest);

    // 返回结果处理
    System.out.println("RequestId: " + updateRowResponse.getRequestId());
    System.out.println("Read CU Cost: " + updateRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
    System.out.println("Write CU Cost: " + updateRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());
}

您也可以参照示例代码进行以下行数据操作。

  • 添加一个属性列

    rowUpdateChange.put("col2", ColumnValue.fromString("val2"));
  • 设置属性列数据版本号

    rowUpdateChange.put("col2", ColumnValue.fromString("val2"), System.currentTimeMillis());
  • 删除属性列指定版本的数据

    rowUpdateChange.deleteColumn("col2", 1747893563831L);
  • 删除整个属性列数据

    rowUpdateChange.deleteColumns("col2");

相关文档