写入单行数据

更新时间:
复制为 MD 格式

本文介绍如何通过 Go SDK 在表格存储的数据表中写入单行数据。

前提条件

初始化Tablestore Client

方法说明

func (tableStoreClient *TableStoreClient) PutRow(request *PutRowRequest) (*PutRowResponse, error)

PutRowRequest参数说明

  • PutRowChange(必选)*PutRowChange:写入的行数据信息,包含以下参数。

    名称

    类型

    说明

    TableName(必选)

    string

    数据表名称。

    PrimaryKey(必选)

    *PrimaryKey

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

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

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

    • 主键列为自增列时,需将该列的值设置为占位符,详情请参见主键列自增

    Columns(可选)

    []AttributeColumn

    属性列信息,包括属性列名称、属性列值和数据版本号。

    • 属性列数据类型包括 STRING、INTEGER、BINARY、DOUBLE 和 BOOLEAN。

    • 数据版本号即时间戳,默认由系统自动生成,也可以自行指定,详情请参见数据版本和生命周期

    Condition(必选)

    *RowCondition

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

    ReturnType(可选)

    ReturnType

    返回类型。

    • ReturnType_RT_NONE:默认值,不返回数据。

    • ReturnType_RT_PK:返回主键列,可以用于主键列自增。

    • ReturnType_RT_AFTER_MODIFY:返回更改后的列值,用于原子计数器

    TransactionId(可选)

    *string

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

示例代码

以下示例代码在 test_table 表中写入一行数据,该行数据的主键值为 row1。

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

    // 构造写入行数据
    putRowChange := new(tablestore.PutRowChange)
    putRowChange.TableName = "test_table"
    putRowChange.PrimaryKey = putPk
    // 写入数据时必须指定写入条件 (RowExistenceExpectation_IGNORE,表示不做行存在性判断)
    putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)

    // 调用 PutRow 方法写入行数据
    putRowRequest := new(tablestore.PutRowRequest)
    putRowRequest.PutRowChange = putRowChange
    response, err := client.PutRow(putRowRequest)
    if err != nil {
        fmt.Println("Put 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)
    }
}
  • 添加属性列。

    putRowChange.AddColumn("col1", "val1")
  • 指定数据版本号,您可以为每个属性列指定单独的版本号。

    putRowChange.AddColumnWithTimestamp("col1", "val1", int64(time.Now().Unix() * 1000))
    putRowChange.AddColumnWithTimestamp("col2", int64(3), int64(1758249013000))

相关文档

批量更新数据