更新单行数据

更新时间:
复制为 MD 格式

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

前提条件

初始化Tablestore Client

方法说明

func (tableStoreClient *TableStoreClient) UpdateRow(request *UpdateRowRequest) (*UpdateRowResponse, error)

UpdateRowRequest参数说明

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

    名称

    类型

    说明

    TableName(必选)

    string

    数据表名称。

    PrimaryKey(必选)

    *PrimaryKey

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

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

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

    Columns(必选)

    []ColumnToUpdate

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

    Condition(必选)

    *RowCondition

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

    TransactionId(可选)

    *string

    局部事务ID,用于唯一标识局部事务,详情请参见局部事务

示例代码

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

func UpdateRowSample(client *tablestore.TableStoreClient) {
    // 构造主键
    updatePk := new(tablestore.PrimaryKey)
    updatePk.AddPrimaryKeyColumn("id", "row1")

    // 构造更新行数据
    updateRowChange := new(tablestore.UpdateRowChange)
    updateRowChange.TableName = "test_table"
    updateRowChange.PrimaryKey = updatePk
    updateRowChange.PutColumn("col1", "changed_val1")
    // 更新行数据时必须指定更新条件 (tablestore.RowExistenceExpectation_IGNORE,表示不做行存在性判断)
    updateRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)

    // 调用 UpdateRow 方法更新行数据
    updateRowRequest := new(tablestore.UpdateRowRequest)
    updateRowRequest.UpdateRowChange = updateRowChange
    response, err := client.UpdateRow(updateRowRequest)
    if err != nil {
        fmt.Println("Update row failed with error: ", err)
    } else {
        fmt.Printf("RequestId: %s \n", response.RequestId)
        fmt.Printf("Read CU Cost: %d \n", response.ConsumedCapacityUnit.Read)
        fmt.Printf("Write CU Cost: %d \n", response.ConsumedCapacityUnit.Write)
    }
}

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

  • 添加一个属性列。

    updateRowChange.PutColumn("col2", "val2")
  • 设置属性列数据版本号。

    updateRowChange.PutColumnWithTimestamp("col2", "val2", int64(time.Now().Unix() * 1000))
    updateRowChange.PutColumnWithTimestamp("col2", int64(1), int64(1758249013000))
  • 删除属性列指定版本的数据。

    updateRowChange.DeleteColumnWithTimestamp("col2", 1747893563831)
  • 删除整个属性列数据。

    updateRowChange.DeleteColumn("col2")

相关文档