全部產品
Search
文件中心

Tablestore:寫入單行資料

更新時間:Aug 05, 2026

使用 Python SDK 寫入單行資料,並按需設定寫入條件、資料版本號碼和局部事務。

前提條件

安裝Tablestore Python SDK並初始化用戶端。

功能說明

調用 put_row 方法寫入單行資料。如果主鍵已存在,該方法覆蓋該行;如果主鍵不存在,該方法新增一行。

def put_row(
    self,
    table_name,
    row,
    condition=None,
    return_type=None,
    transaction_id=None,
)

以下樣本向 example_table 寫入主鍵為 ("device", 1) 的一行資料。

primary_key = [("partition", "device"), ("id", 1)]
attribute_columns = [("name", "thermometer"), ("status", "online")]
row = Row(primary_key, attribute_columns)
condition = Condition(RowExistenceExpectation.IGNORE)

consumed, return_row = client.put_row(
    "example_table",
    row,
    condition,
)
print("Write CU: %s" % consumed.write)

參數說明

put_row 方法包含以下參數。

名稱

類型

說明

table_name(必選)

str

資料表名稱。

row(必選)

Row

待寫入的主鍵和屬性列。

condition(可選)

Condition

寫入條件。預設不判斷行是否存在。有關條件的配置方法,請參見條件更新。

return_type(可選)

ReturnType

傳回型別。RT_NONE(預設值)表示不返回資料;RT_PK 表示返回主鍵列,常用於擷取自增主索引值。

transaction_id(可選)

str

局部事務 ID。僅在局部事務內寫入資料時設定。有關局部事務的使用方法,請參見局部事務。

行資料

row 的類型為 Row,包含以下參數。

名稱

類型

說明

primary_key(必選)

List[Tuple]

主鍵資訊。主鍵列的名稱、順序、數量和類型必須與資料表的主鍵結構一致。

attribute_columns(可選)

List[Tuple]

屬性列列表。每個元素為 (column_name, column_value) 或 (column_name, column_value, timestamp)。屬性列值支援 str、int、bytes、float 和 bool 類型。未指定 timestamp 時,服務端自動產生資料版本號碼。

傳回值

put_row 返回以下值。

欄位

類型

說明

consumed

CapacityUnit

本次操作消耗的讀寫 CU。

return_row

Row

返回的行資料。return_type 為 RT_PK 時返回主鍵列,否則為 None。

情境樣本

寫入多個屬性列

以下樣本寫入字串、整數和布爾類型的屬性列。

primary_key = [("partition", "device"), ("id", 2)]
attribute_columns = [
    ("name", "humidity-sensor"),
    ("temperature", 26),
    ("enabled", True),
]
row = Row(primary_key, attribute_columns)

client.put_row(
    "example_table",
    row,
    Condition(RowExistenceExpectation.IGNORE),
)

指定資料版本號碼

屬性列元組的第三個元素用於指定資料版本號碼,單位為毫秒。版本號碼必須處於資料表允許的有效版本範圍內。

timestamp = int(time.time() * 1000)
primary_key = [("partition", "device"), ("id", 3)]
attribute_columns = [
    ("status", "online", timestamp),
    ("temperature", 25, timestamp),
]
row = Row(primary_key, attribute_columns)

client.put_row(
    "example_table",
    row,
    Condition(RowExistenceExpectation.IGNORE),
)

擷取自增主索引值

向包含自增主鍵列的資料表寫入資料時,將該列的值設定為 PK_AUTO_INCR,並將 return_type 設定為 RT_PK。有關自增主鍵列的配置要求,請參見主鍵列自增。

primary_key = [("partition", "device"), ("id", PK_AUTO_INCR)]
row = Row(primary_key, [("name", "pressure-sensor")])

consumed, return_row = client.put_row(
    "example_table",
    row,
    Condition(RowExistenceExpectation.IGNORE),
    ReturnType.RT_PK,
)
print(return_row.primary_key)