使用 API 添加表数据
向表中添加行。将数据存储在表行中时,应用程序可以轻松地从表中检索、添加或删除信息。
可以使用 PutRequest 类/put 方法执行无条件和有条件放置,以便:
-
覆盖任何现有行。覆盖是默认功能。
-
仅当行不存在时才成功。在这种情况下,请使用
IfAbsent方法。 -
仅当行存在时才成功。在这种情况下,请使用
IfPresent方法。 -
仅当行存在且版本与特定版本匹配时才成功。对此情况使用
IfVersion方法,使用setMatchVersion方法指定要匹配的版本。
PutRequest 类提供了 setValueFromJson 方法,该方法接受 JSON 字符串并使用该字符串填充要插入表中的行。JSON 字符串应指定与表字段名称对应的字段名称。
Download the full code AddData.java from the examples here.
private static void writeRows(NoSQLHandle handle, MapValue value)
throws Exception {
PutRequest putRequest =
new PutRequest().setValue(value).setTableName(tableName);
PutResult putResult = handle.put(putRequest);
if (putResult.getVersion() != null) {
System.out.println("Added a row to the stream_acct table");
} else {
System.out.println("Put failed");
}
}
将数据插入到 JSON 集合表中:
您可以使用一系列 PutRequest 操作将顶层文档字段插入到 JSON 集合表中。对于嵌套 JSON 字段,您可以将 JSON 数据作为字符串提供给 putFromJson 操作。
以下代码示例说明将数据作为 JSON 集合表创建时如何将数据插入 stream_acct 表。
String tableName = "stream_acct";
MapValue value = new MapValue()
.put("acct_Id", 1)
.put("profile_name", "AP")
.put("account_expiry", "2023-10-18")
.putFromJson(
"acct_data",
"{\"firstName\":\"Adam\","
+ "\"lastName\":\"Philip\","
+ "\"country\":\"Germany\"}",
null);
PutRequest putRequest = new PutRequest()
.setValue(value)
.setTableName(tableName);
PutResult putRes = handle.put(putRequest);
System.out.println("Put row: " + value + " result=" + putRes);
borneo.PutRequest 类表示 borneo.NoSQLHandle.put() 方法的输入,该方法用于插入单个行。
您还可以向表中添加 JSON 数据。对于固定模式表,JSON 将转换为目标模式。JSON 数据可以直接插入到 JSON 类型的列中。通过使用 JSON 数据类型,您可以在没有固定模式的情况下创建表数据,从而更灵活地使用数据。
Download the full code AddData.py from the examples here.
def insert_record(handle,table_name,acct_data):
request = PutRequest().set_table_name(table_name)
.set_value_from_json(acct_data)
handle.put(request)
print('Added a row to the stream_acct table')
将数据插入到 JSON 集合表中:
可以将行作为 JSON 字符串直接添加到 JSON 集合表中。
以下代码示例说明如何将数据作为 JSON 集合表创建时插入到 stream_acct 表中。
import json
from borneo import PutRequest
table_name = "stream_acct"
row = {
"acct_Id": 1,
"profile_name": "AP",
"account_expiry": "2023-10-18",
"acct_data": {
"firstName": "Adam",
"lastName": "Philip",
"country": "Germany"
}
}
request = (
PutRequest()
.set_table_name(table_name)
.set_value_from_json(json.dumps(row))
)
result = handle.put(request)
print("Put row:", row, "result:", result)
nosqldb.PutRequest 表示 nosqldb.Put() 函数的输入,用于插入单行。
为行提供的数据值(在 PutRequest 中)为 *types.MapValue。MapValue 中每个条目的 key 部分必须与目标表的列名匹配,value 部分必须为列的有效值。JSON 数据也可以直接插入 JSON 类型的列。通过使用 JSON 数据类型,您可以在没有固定模式的情况下创建表数据,从而更灵活地使用数据。
Download the full code AddData.go from the examples here.
func insertData(client *nosqldb.Client, err error,
tableName string,value1 *types.MapValue )(){
putReq := &nosqldb.PutRequest{
TableName: tableName,
Value: value1,
}
putRes, err := client.Put(putReq)
if err != nil {
fmt.Printf("failed to put single row: %v\n", err)
return
}
fmt.Printf("Added a row to the stream_acct table\n")
}
将数据插入到 JSON 集合表中:
您可以从 JSON 数据创建映射值,并将该行添加到 JSON 集合表中。
以下代码示例说明如何将数据作为 JSON 集合表创建时插入到 stream_acct 表中。
tableName := "stream_acct"
rowJSON := `{
"acct_Id": 1,
"profile_name": "AP",
"account_expiry": "2023-10-18",
"acct_data": {
"firstName": "Adam",
"lastName": "Philip",
"country": "Germany"
}
}`
value, err := types.NewMapValueFromJSON(rowJSON)
if err != nil {
return fmt.Errorf("invalid row JSON: %w", err)
}
request := &nosqldb.PutRequest{
TableName: tableName,
Value: value,
}
result, err := client.Put(request)
可以使用 put 方法向表中插入单个行。有关方法详细信息,请参见 NoSQLClient 类。
JavaScript: Download the full code AddData.js from the examples here.
/* Adding 3 records in acct_stream table */
let putResult = await handle.put(TABLE_NAME, JSON.parse(acct1));
let putResult1 = await handle.put(TABLE_NAME, JSON.parse(acct2));
let putResult2 = await handle.put(TABLE_NAME, JSON.parse(acct3));
console.log("Added rows to the stream_acct table");
TypeScript:从此处的示例下载完整代码 AddData.ts。
interface StreamInt {
acct_Id: Integer;
profile_name: String;
account_expiry: TIMESTAMP;
acct_data: JSON;
}
/* Adding 3 records in acct_stream table */
let putResult = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct1));
let putResult1 = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct2));
let putResult2 = await handle.put<StreamInt>(TABLE_NAME, JSON.parse(acct3));
console.log("Added rows to the stream_acct table");
将数据插入到 JSON 集合表中:
您可以向 JSON 集合表中添加行,方法是提供支持的 JSON 类型的普通 JavaScript 对象。
以下代码示例说明如何将数据作为 JSON 集合表创建时插入到 stream_acct 表中。
import { NoSQLClient } from 'oracle-nosqldb';
const client = new NoSQLClient('config.json');
const TABLE_NAME = 'stream_acct';
const record = {
acct_Id: 1,
profile_name: 'AP',
account_expiry: '2023-10-18',
acct_data: {
firstName: 'Adam',
lastName: 'Philip',
country: 'Germany'
}
};
async function writeARecord(client, record) {
await client.put(TABLE_NAME, record);
console.log('Added a row to the stream_acct table');
}
await writeARecord(client, record);
方法 PutAsync 和相关方法 PutIfAbsentAsync、PutIfPresentAsync 和 PutIfVersionAsync 用于将单个行插入表中或更新单个行。
上面的每个 Put 方法都返回 Task<PutResult<RecordValue>>。PutResult 实例包含有关已完成 Put 操作的信息,例如成功状态(如果未满足相应条件,条件放置操作可能会失败)和生成的 RowVersion。请注意,结果的成功属性仅表示与条件 Put 操作相关的成功完成,对于无条件 Put 始终为 true。如果 Put 操作因任何其他原因而失败,则会引发异常错误。使用 JSON 数据类型的字段可以更灵活地使用数据,因为 JSON 字段中的数据没有预定义的模式。要将值放入 JSON 字段,请提供 MapValue 实例作为其字段值作为行值的一部分。您也可以通过 FieldValue.FromJsonString 从 JSON 字符串创建其值。
Download the full code AddData.cs from the examples here.
private static async Task insertData(NoSQLClient client, String acctdet){
var putResult = await client.PutAsync(TableName,
FieldValue.FromJsonString(acctdet).AsMapValue);
if (putResult.ConsumedCapacity != null)
{
Console.WriteLine(" Added a row to the stream_acct table");
}
}
将数据插入到 JSON 集合表中:
通过从通过 FromJsonString 方法创建的 JSON 字符串中放置其值,可以在 JSON 集合表中添加行。
以下代码示例说明如何将数据作为 JSON 集合表创建时插入到 stream_acct 表中。
var tableName = "stream_acct";
const string data = @"{
""acct_Id"": 1,
""profile_name"": ""AP"",
""account_expiry"": ""2023-10-18"",
""acct_data"": {
""firstName"": ""Adam"",
""lastName"": ""Philip"",
""country"": ""Germany""
}
}";
var result = await client.PutAsync(
tableName,
FieldValue.FromJsonString(data).AsMapValue
);
Console.WriteLine("Added a row to the stream_acct table");
您可以使用 MultiWrite API 在单个数据库操作中添加多个数据行。
您可以使用 WriteMultipleRequest 类执行与表关联的 PutRequest 操作序列,该表与单个原子写入操作共享其主键的同一分片密钥部分。还可以使用 WriteMultipleRequest 类同时向父表和子表添加数据。这是以原子方式修改多个相关行的有效方法。如果操作成功,则 WriteMultipleResult.getSuccess() 方法返回 true。
有关各种类和方法的更多详细信息,请参阅 Oracle NoSQL Java SDK API Reference 。
Download the full code MultiWrite.java from the examples here.
private static void writeMul(NoSQLHandle handle,String parent_tblname,
String parent_data, String child_tblname, String child_data){
WriteMultipleRequest umRequest = new WriteMultipleRequest();
PutRequest putRequest =
new PutRequest().setValueFromJson(parent_data,null).setTableName(parent_tblname);
umRequest.add(putRequest, false);
putRequest =
new PutRequest().setValueFromJson(child_data,null).setTableName(child_tblname);
umRequest.add(putRequest, false);
WriteMultipleResult umResult = handle.writeMultiple(umRequest);
}
您可以使用 borneo.WriteMultipleRequest 类执行与表关联的 PutRequest 操作序列,该表与单个原子写入操作共享其主键的同一分片密钥部分。还可以使用 borneo.WriteMultipleRequest 类同时向父表和子表添加数据。这是以原子方式修改多个相关行的有效方法。
有关各种类和方法的更多详细信息,请参阅 Oracle NoSQL Python SDK API Reference 。
Download the full code MultiWrite.py from the examples here.
def mul_write(handle,parent_tblname,parent_data,
child_tblname, child_data):
request = PutRequest()
request.set_value_from_json(parent_data)
request.set_table_name('ticket')
wm_req.add(request, True)
request1 = PutRequest()
request1.set_table_name(child_tblname)
request1.set_value_from_json(child_data)
wm_req.add(request1, True)
result = handle.write_multiple(wm_req)
您可以使用 WriteMultipleRequest 类执行与表关联的 PutRequest 操作序列,该表与单个原子写入操作共享其主键的同一分片密钥部分。还可以使用 WriteMultipleRequest 类同时向父表和子表添加数据。这是以原子方式修改多个相关行的有效方法。
有关各种类和方法的更多详细信息,请参阅 Oracle NoSQL Go SDK API Reference 。
Download the full code MultiWrite.go from the examples here.
//multiple write from the table
func mul_write(client *nosqldb.Client, err error, parenttbl_name string,
parent_data string, childtbl_name string, child_data string)(){
value, err := types.NewMapValueFromJSON(parent_data)
putReq := &nosqldb.PutRequest{
TableName: parenttbl_name,
Value: value,
}
wmReq := &nosqldb.WriteMultipleRequest{
TableName: "",
Timeout: 10 * time.Second,
}
wmReq.AddPutRequest(putReq, true)
value1, err := types.NewMapValueFromJSON(child_data)
putReq1 := &nosqldb.PutRequest{
TableName: childtbl_name,
Value: value1,
}
wmReq.AddPutRequest(putReq1, true)
wmRes, err := client.WriteMultiple(wmReq)
if err != nil {
fmt.Printf("WriteMultiple() failed: %v\n", err)
return
}
if wmRes.IsSuccess() {
fmt.Printf("WriteMultiple() succeeded\n")
} else {
fmt.Printf("WriteMultiple() failed\n")
}
}
可以使用 writeMany 方法执行与表关联的 put 操作序列,该表与单个原子写入操作共享其主键的同一分片密钥部分。还可以使用 writeMany 方法同时向父表和子表添加数据。这是以原子方式修改多个相关行的有效方法。
有关方法详细信息,请参见 NoSQLClient 类。
JavaScript: Download the full code MultiWrite.js from the examples here.
const ops = [
{
tableName: 'ticket',
put: {
"ticketNo": "1762344493810",
"confNo" : "LE6J4Z"
},
abortOnFail: true
},
{
tableName: 'ticket.bagInfo',
put: {
"ticketNo":"1762344493810",
"id":"79039899165297",
"tagNum":"17657806255240",
"routing":"MIA/LAX/MEL",
"lastActionCode":"OFFLOAD",
"lastActionDesc":"OFFLOAD",
"lastSeenStation":"MEL",
"lastSeenTimeGmt":"2019-02-01T16:13:00Z",
"bagArrivalDate":"2019-02-01T16:13:00Z"
},
abortOnFail: true
}
];
const res = await handle.writeMany(ops, null);
TypeScript:从此处的示例下载完整代码 MultiWrite.ts。
const ops = [
{
tableName: 'ticket',
put: {
"ticketNo": "1762344493810",
"confNo" : "LE6J4Z"
},
abortOnFail: true
},
{
tableName: 'ticket.bagInfo',
put: {
"ticketNo":"1762344493810",
"id":"79039899165297",
"tagNum":"17657806255240",
"routing":"MIA/LAX/MEL",
"lastActionCode":"OFFLOAD",
"lastActionDesc":"OFFLOAD",
"lastSeenStation":"MEL",
"lastSeenTimeGmt":"2019-02-01T16:13:00Z",
"bagArrivalDate":"2019-02-01T16:13:00Z"
},
abortOnFail: true
}
];
const res = await handle.writeMany(ops, null);
可以使用 PutManyAsync 方法执行与表关联的 put 操作序列,该表与单个原子写入操作共享其主键的同一分片密钥部分。还可以使用 PutManyAsync 方法同时向父表和子表添加数据。这是以原子方式修改多个相关行的有效方法。
有关所有类和方法的更多详细信息,请参阅 Oracle NoSQL Dotnet SDK API Reference 。
Download the full code MultiWrite.cs from the examples here.
private static async Task mul_write(NoSQLClient client,string parentbl_name,
string data1, string childtbl_name, string data2){
var result = await client.WriteManyAsync(
new WriteOperationCollection()
.AddPut(parentbl_name, FieldValue.FromJsonString(data1).AsMapValue)
.AddPut(childtbl_name, FieldValue.FromJsonString(data2).AsMapValue)
);
}