本文介绍如何通过 Java SDK 更新表格存储数据表中的单行数据,您可以更新属性列的值、添加属性列、删除属性列的某个版本或整个属性列。
前提条件
方法说明
public UpdateRowResponse updateRow(UpdateRowRequest updateRowRequest) throws TableStoreException, ClientException
示例代码
以下示例代码用于修改 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");
相关文档
该文章对您有帮助吗?