本文主要为您介绍如何通过表格存储的Go SDK在创建表时添加主键自增列并写入数据。

说明
  • 若设置数据表的某一列主键为自增列,在写入一行数据时,这一列主键无需填值,表格存储会自动生成这一主键列的值。
  • 自增列的值唯一,且严格递增。
  • 每张表最多只允许设置一个主键为自增列。
  • 分区键和属性列不允许设置为自增列。

创建表

您可以在创建表的同时添加主键自增列,示例如下:

import (
    "fmt"
    "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

func CreateTableKeyAutoIncrementSample(client *tablestore.TableStoreClient) {
    createtableRequest := new(tablestore.CreateTableRequest)
    // 创建表,此表包括三个主键:pk1,String类型;pk2,INTEGER类型,为自增列;pk3,Binary类型。
    tableMeta := new(tablestore.TableMeta)
    tableMeta.TableName = "incrementsampletable"
    tableMeta.AddPrimaryKeyColumn("pk1", tablestore.PrimaryKeyType_STRING)
    tableMeta.AddPrimaryKeyColumnOption("pk2", tablestore.PrimaryKeyType_INTEGER, tablestore.AUTO_INCREMENT)
    tableMeta.AddPrimaryKeyColumn("pk3", tablestore.PrimaryKeyType_BINARY)
    tableOption := new(tablestore.TableOption)
    tableOption.TimeToAlive = -1
    tableOption.MaxVersion = 3
    reservedThroughput := new(tablestore.ReservedThroughput)
    reservedThroughput.Readcap = 0
    reservedThroughput.Writecap = 0
    createtableRequest.TableMeta = tableMeta
    createtableRequest.TableOption = tableOption
    createtableRequest.ReservedThroughput = reservedThroughput

    client.CreateTable(createtableRequest)
}

写入数据

示例如下:

import (
    "fmt"
    "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

func PutRowWithKeyAutoIncrementSample(client *tablestore.TableStoreClient) {
    fmt.Println("begin to put row")
    putRowRequest := new(tablestore.PutRowRequest)
    putRowChange := new(tablestore.PutRowChange)
    putRowChange.TableName = "incrementsampletable"
    // 设置主键,必须按照创建表时的顺序添加主键,并且需要指定pk2为自增主键。
    putPk := new(tablestore.PrimaryKey)
    putPk.AddPrimaryKeyColumn("pk1", "pk1value1")
    putPk.AddPrimaryKeyColumnWithAutoIncrement("pk2")
    putPk.AddPrimaryKeyColumn("pk3", []byte("pk3"))
    putRowChange.PrimaryKey = putPk
    putRowChange.AddColumn("col1", "col1data1")
    putRowChange.AddColumn("col2", int64(100))
    putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)
    putRowRequest.PutRowChange = putRowChange
    _, err := client.PutRow(putRowRequest)

    if err != nil {
        fmt.Println("put row failed with error:", err)
    } else {
        fmt.Println("put row finished")
    }
}