全部產品
Search
文件中心

Tablestore:寫入單行資料

更新時間:Apr 01, 2026

本文介紹如何通過 Go SDK 在Table Store的資料表中寫入單行資料。

前提條件

初始化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))

相關文檔

批次更新資料