本文主要为您介绍如何通过表格存储的Node.js SDK在创建表时添加主键自增列并写入数据。
说明
- 若设置数据表的某一列主键为自增列,在写入一行数据时,这一列主键无需填值,表格存储会自动生成这一主键列的值。
- 自增列的值唯一,且严格递增。
- 每张表最多只允许设置一个主键为自增列。
- 分区键和属性列不允许设置为自增列。
创建表
您可以在创建表的同时添加主键自增列,示例如下:
var TableStore = require('../index.js');
var Long = TableStore.Long;
var client = require('./client');
var tableName = "autoIncTable";
var pk1 = "stringPK";
var pk2 = "autoIncPK";
function createTableWithAutoIncrementPk() {
var createParams = {
tableMeta: {
tableName: tableName,
primaryKey: [
{
name: pk1,
type: 'STRING'
},
{
name: pk2,
type: 'INTEGER',
option: 'AUTO_INCREMENT'//自增列,指定otpion为AUTO_INCREMENT
},
]
},
reservedThroughput: {
capacityUnit: {
read: 0,
write: 0
}
},
tableOptions: {
timeToLive: -1,// 数据的过期时间, 单位秒, -1代表永不过期. 假如设置过期时间为一年, 即为 365 * 24 * 3600.
maxVersions: 1// 保存的最大版本数, 设置为1即代表每列上最多保存一个版本(保存最新的版本).
},
};
client.createTable(createParams, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('create table success');
});
}
写入数据
示例如下:
var TableStore = require('../index.js');
var Long = TableStore.Long;
var client = require('./client');
var tableName = "autoIncTable";
var pk1 = "stringPK";
var pk2 = "autoIncPK";
function putRow() {
var putParams = {
tableName: tableName,
condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
primaryKey: [
{ stringPK: 'pk1' },
{ autoIncPK: TableStore.PK_AUTO_INCR }
],
attributeColumns: [
{ 'col1': 'col1val' }
],
returnContent: { returnType: TableStore.ReturnType.Primarykey }
};
client.putRow(putParams, function (err, data) {
if (err) {
console.log('error:', err);
return;
}
console.log('put row success,autoIncrement pk value:' + JSON.stringify(data.row.primaryKey));
});
}
在文档使用中是否遇到以下问题
更多建议
匿名提交