As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Driver Amazon QLDB para.NET: tutorial de início rápido
Neste tutorial, você aprenderá como configurar um aplicativo simples usando a versão mais recente do driver QLDB da Amazon para .NET. Este guia inclui etapas para instalação do driver e exemplos de códigos curtos de operações básicas de criação, leitura, atualização e exclusão (CRUD).
Pré-requisitos
Antes de iniciar, certifique-se de fazer o seguinte:
Etapa 1: configurar o projeto do
Primeiro, configure seu projeto .NET.
-
Para criar e executar um aplicativo modelo, digite os seguintes dotnet
comandos em um terminal PowerShell, como bash ou prompt de comando.
$
dotnet new console --output Amazon.QLDB.QuickStartGuide
$
dotnet run --project Amazon.QLDB.QuickStartGuide
Esse modelo cria uma pasta chamadaAmazon.QLDB.QuickStartGuide
. Nessa pasta, ele cria um projeto com o mesmo nome e um arquivo chamado Program.cs
. O programa contém código que exibe a saída Hello World!
.
-
Use o gerenciador de NuGet pacotes para instalar o driver QLDB para.NET. Recomendamos usar o Visual Studio ou um IDE de sua escolha para adicionar dependências ao seu projeto. O nome do pacote do driver é Amazon.QLDB.Driver.
-
Por exemplo, no Visual Studio, abra o NuGet Package Manager Console no menu Tools. Então, digite o seguinte comando no PM>
prompt:
PM>
Install-Package Amazon.QLDB.Driver
-
Ou, é possível inserir os comandos a seguir no terminal.
$
cd Amazon.QLDB.QuickStartGuide
$
dotnet add package Amazon.QLDB.Driver
A instalação do driver também instala suas dependências, incluindo os pacotes AWS SDK for .NET e Amazon Ion.
-
Instale a biblioteca de serialização do driver.
PM>
Install-Package Amazon.QLDB.Driver.Serialization
-
Abra o arquivo Program.cs
.
Em seguida, adicione incrementalmente os exemplos de código nas etapas a seguir para experimentar algumas operações básicas de CRUD. Ou você pode pular o step-by-step tutorial e, em vez disso, executar o aplicativo completo.
-
Escolha entre síncrono e assíncrono APIs — O driver fornece síncrono e assíncrono. APIs Para aplicativos de alta demanda que lidam com várias solicitações sem bloqueio, recomendamos usar o APIs assíncrono para melhorar o desempenho. O driver oferece síncrono APIs como uma conveniência adicional para bases de código existentes que são escritas de forma síncrona.
Este tutorial inclui exemplos de código síncrono e assíncrono. Para obter mais informações sobre o APIs, consulte o IQldbdriver e IAsyncQldbDriveras interfaces na documentação da API.
-
Processamento de dados Amazon Ion: este tutorial fornece exemplos de código de processamento de dados do Amazon Ion usando o mapeador de objetos Ion por padrão. O QLDB introduziu o mapeador de objetos Ion na versão 1.3.0 do driver .NET. Onde aplicável, este tópico também fornece exemplos de código usando a biblioteca Ion padrão como alternativa. Para saber mais, consulte Como trabalhar com o Amazon Ion.
Etapa 2: Inicializar o driver
Inicialize uma instância do driver que se conecta ao ledger chamado quick-start
. Adicione o seguinte código ao arquivo Program.cs
.
- Async
-
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return FirstName + ", " + LastName + ", " + Age.ToString();
}
}
static async Task Main(string[] args)
{
Console.WriteLine("Create the async QLDB driver");
IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
.WithLedger("quick-start")
.WithSerializer(new ObjectSerializer())
.Build();
}
}
}
- Sync
-
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return FirstName + ", " + LastName + ", " + Age.ToString();
}
}
static void Main(string[] args)
{
Console.WriteLine("Create the sync QLDB driver");
IQldbDriver driver = QldbDriver.Builder()
.WithLedger("quick-start")
.WithSerializer(new ObjectSerializer())
.Build();
}
}
}
- Async
-
using System;
using System.Threading.Tasks;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
static IValueFactory valueFactory = new ValueFactory();
static async Task Main(string[] args)
{
Console.WriteLine("Create the async QLDB driver");
IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
.WithLedger("quick-start")
.Build();
}
}
}
- Sync
-
using System;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
static IValueFactory valueFactory = new ValueFactory();
static void Main(string[] args)
{
Console.WriteLine("Create the sync QLDB Driver");
IQldbDriver driver = QldbDriver.Builder()
.WithLedger("quick-start")
.Build();
}
}
}
Etapa 3: Crie uma tabela e um índice
Para o restante deste tutorial até a Etapa 6, você precisa acrescentar os exemplos de código a seguir ao exemplo de código anterior.
Os exemplos de código a seguir mostram como executar as instruções CREATE TABLE
e CREATE INDEX
. Adicione o código a seguir que cria uma tabela chamada Person
e um índice para o campo firstName
nessa tabela. Os índices são necessários para otimizar o desempenho da consulta e ajudar a limitar as exceções de conflitos de controle de simultaneidade otimista (OCC).
- Async
-
Console.WriteLine("Creating the table and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
await driver.Execute(async txn =>
{
await txn.Execute("CREATE TABLE Person");
await txn.Execute("CREATE INDEX ON Person(firstName)");
});
- Sync
-
Console.WriteLine("Creating the tables and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
driver.Execute(txn =>
{
txn.Execute("CREATE TABLE Person");
txn.Execute("CREATE INDEX ON Person(firstName)");
});
Etapa 4: Inserir um documento
O exemplo de código a seguir mostra como executar uma instrução INSERT
. O QLDB suporta a linguagem de consulta partiQL (compatível com SQL) e o formato de dados Amazon Ion (superconjunto de JSON).
Adicione o código a seguir que insere um documento na tabela Person
.
- Async
-
Console.WriteLine("Inserting a document");
Person myPerson = new Person {
FirstName = "John",
LastName = "Doe",
Age = 32
};
await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
await txn.Execute(myQuery);
});
- Sync
-
Console.WriteLine("Inserting a document");
Person myPerson = new Person {
FirstName = "John",
LastName = "Doe",
Age = 32
};
driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
txn.Execute(myQuery);
});
- Async
-
Console.WriteLine("Inserting a document");
// This is one way of creating Ion values. We can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));
await driver.Execute(async txn =>
{
await txn.Execute("INSERT INTO Person ?", ionPerson);
});
- Sync
-
Console.WriteLine("Inserting a document");
// This is one way of creating Ion values, we can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));
driver.Execute(txn =>
{
txn.Execute("INSERT INTO Person ?", ionPerson);
});
Para inserir vários documentos usando uma única instrução INSERT, você pode passar um parâmetro do tipo lista Ion para a instrução da seguinte maneira.
// people is an Ion list
txn.Execute("INSERT INTO Person ?", people);
Você não coloca o marcador variável (?
) entre colchetes angulares duplos (<<...>>
) ao passar uma lista Ion. Nas instruções manuais do PartiQL, colchetes angulares duplos denotam uma coleção não ordenada conhecida como bolsa.
Etapa 5: consultar o documento
O exemplo de código a seguir mostra como executar uma instrução SELECT
.
Adicione o código a seguir que insere um documento da tabela Person
.
- Async
-
Console.WriteLine("Querying the table");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult<Person> selectResult = await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return await txn.Execute(myQuery);
});
await foreach (Person person in selectResult)
{
Console.WriteLine(person);
// John, Doe, 32
}
- Sync
-
Console.WriteLine("Querying the table");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult<Person> selectResult = driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return txn.Execute(myQuery);
});
foreach (Person person in selectResult)
{
Console.WriteLine(person);
// John, Doe, 32
}
- Async
-
Console.WriteLine("Querying the table");
IIonValue ionFirstName = valueFactory.NewString("John");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult selectResult = await driver.Execute(async txn =>
{
return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});
await foreach (IIonValue row in selectResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
- Sync
-
Console.WriteLine("Querying the table");
IIonValue ionFirstName = valueFactory.NewString("John");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult selectResult = driver.Execute(txn =>
{
return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});
foreach (IIonValue row in selectResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
Este exemplo usa um ponto de interrogação (?
) como um marcador variável para passar as informações do documento para a instrução. Ao usar espaços reservados, você deve passar um valor do tipo IonValue
.
Etapa 6: Atualize o documento
O exemplo de código a seguir mostra como executar uma instrução UPDATE
.
-
Adicione o código a seguir que insere um documento na tabela Person
, atualizando age
para 42.
- Async
-
Console.WriteLine("Updating the document");
await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
await txn.Execute(myQuery);
});
- Sync
-
Console.WriteLine("Updating the document");
driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
txn.Execute(myQuery);
});
-
Consulte a tabela novamente para ver o valor atualizado.
- Async
-
Console.WriteLine("Querying the table for the updated document");
IAsyncResult<Person> updateResult = await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return await txn.Execute(myQuery);
});
await foreach (Person person in updateResult)
{
Console.WriteLine(person);
// John, Doe, 42
}
- Sync
-
Console.WriteLine("Querying the table for the updated document");
IResult<Person> updateResult = driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return txn.Execute(myQuery);
});
foreach (Person person in updateResult)
{
Console.WriteLine(person);
// John, Doe, 42
}
-
Para executar o aplicativo, insira o comando a seguir do diretório Amazon.QLDB.QuickStartGuide
do seu projeto.
$
dotnet run --project Amazon.QLDB.QuickStartGuide
-
Adicione o código a seguir que insere um documento na tabela Person
, atualizando age
para 42.
- Async
-
Console.WriteLine("Updating the document");
IIonValue ionIntAge = valueFactory.NewInt(42);
IIonValue ionFirstName2 = valueFactory.NewString("John");
await driver.Execute(async txn =>
{
await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
});
- Sync
-
Console.WriteLine("Updating a document");
IIonValue ionIntAge = valueFactory.NewInt(42);
IIonValue ionFirstName2 = valueFactory.NewString("John");
driver.Execute(txn =>
{
txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
});
-
Consulte a tabela novamente para ver o valor atualizado.
- Async
-
Console.WriteLine("Querying the table for the updated document");
IIonValue ionFirstName3 = valueFactory.NewString("John");
IAsyncResult updateResult = await driver.Execute(async txn =>
{
return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3 );
});
await foreach (IIonValue row in updateResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
- Sync
-
Console.WriteLine("Querying the table for the updated document");
IIonValue ionFirstName3 = valueFactory.NewString("John");
IResult updateResult = driver.Execute(txn =>
{
return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
});
foreach (IIonValue row in updateResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
-
Para executar o aplicativo, insira o comando a seguir do diretório Amazon.QLDB.QuickStartGuide
do seu projeto.
$
dotnet run --project Amazon.QLDB.QuickStartGuide
Executar o aplicativo completo
O exemplo de código a seguir é a versão completa do aplicativo Program.cs
. Em vez de executar as etapas anteriores individualmente, você também pode copiar e executar esse exemplo de código do início ao fim. Este aplicativo demonstra algumas operações básicas do CRUD no ledger denominado quick-start
.
Antes de executar esse código, verifique se você ainda não tem uma tabela ativa chamada Person
no ledger quick-start
.
- Async
-
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return FirstName + ", " + LastName + ", " + Age.ToString();
}
}
static async Task Main(string[] args)
{
Console.WriteLine("Create the async QLDB driver");
IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
.WithLedger("quick-start")
.WithSerializer(new ObjectSerializer())
.Build();
Console.WriteLine("Creating the table and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
await driver.Execute(async txn =>
{
await txn.Execute("CREATE TABLE Person");
await txn.Execute("CREATE INDEX ON Person(firstName)");
});
Console.WriteLine("Inserting a document");
Person myPerson = new Person {
FirstName = "John",
LastName = "Doe",
Age = 32
};
await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
await txn.Execute(myQuery);
});
Console.WriteLine("Querying the table");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult<Person> selectResult = await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return await txn.Execute(myQuery);
});
await foreach (Person person in selectResult)
{
Console.WriteLine(person);
// John, Doe, 32
}
Console.WriteLine("Updating the document");
await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
await txn.Execute(myQuery);
});
Console.WriteLine("Querying the table for the updated document");
IAsyncResult<Person> updateResult = await driver.Execute(async txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return await txn.Execute(myQuery);
});
await foreach (Person person in updateResult)
{
Console.WriteLine(person);
// John, Doe, 42
}
}
}
}
- Sync
-
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return FirstName + ", " + LastName + ", " + Age.ToString();
}
}
static void Main(string[] args)
{
Console.WriteLine("Create the sync QLDB driver");
IQldbDriver driver = QldbDriver.Builder()
.WithLedger("quick-start")
.WithSerializer(new ObjectSerializer())
.Build();
Console.WriteLine("Creating the table and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
driver.Execute(txn =>
{
txn.Execute("CREATE TABLE Person");
txn.Execute("CREATE INDEX ON Person(firstName)");
});
Console.WriteLine("Inserting a document");
Person myPerson = new Person {
FirstName = "John",
LastName = "Doe",
Age = 32
};
driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
txn.Execute(myQuery);
});
Console.WriteLine("Querying the table");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult<Person> selectResult = driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return txn.Execute(myQuery);
});
foreach (Person person in selectResult)
{
Console.WriteLine(person);
// John, Doe, 32
}
Console.WriteLine("Updating the document");
driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
txn.Execute(myQuery);
});
Console.WriteLine("Querying the table for the updated document");
IResult<Person> updateResult = driver.Execute(txn =>
{
IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
return txn.Execute(myQuery);
});
foreach (Person person in updateResult)
{
Console.WriteLine(person);
// John, Doe, 42
}
}
}
}
- Async
-
using System;
using System.Threading.Tasks;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
static IValueFactory valueFactory = new ValueFactory();
static async Task Main(string[] args)
{
Console.WriteLine("Create the async QLDB driver");
IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
.WithLedger("quick-start")
.Build();
Console.WriteLine("Creating the table and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
await driver.Execute(async txn =>
{
await txn.Execute("CREATE TABLE Person");
await txn.Execute("CREATE INDEX ON Person(firstName)");
});
Console.WriteLine("Inserting a document");
// This is one way of creating Ion values. We can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));
await driver.Execute(async txn =>
{
await txn.Execute("INSERT INTO Person ?", ionPerson);
});
Console.WriteLine("Querying the table");
IIonValue ionFirstName = valueFactory.NewString("John");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult selectResult = await driver.Execute(async txn =>
{
return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});
await foreach (IIonValue row in selectResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
Console.WriteLine("Updating the document");
IIonValue ionIntAge = valueFactory.NewInt(42);
IIonValue ionFirstName2 = valueFactory.NewString("John");
await driver.Execute(async txn =>
{
await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
});
Console.WriteLine("Querying the table for the updated document");
IIonValue ionFirstName3 = valueFactory.NewString("John");
IAsyncResult updateResult = await driver.Execute(async txn =>
{
return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
});
await foreach (IIonValue row in updateResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
}
}
}
- Sync
-
using System;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
namespace Amazon.QLDB.QuickStartGuide
{
class Program
{
static IValueFactory valueFactory = new ValueFactory();
static void Main(string[] args)
{
Console.WriteLine("Create the sync QLDB Driver");
IQldbDriver driver = QldbDriver.Builder()
.WithLedger("quick-start")
.Build();
Console.WriteLine("Creating the tables and index");
// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
driver.Execute(txn =>
{
txn.Execute("CREATE TABLE Person");
txn.Execute("CREATE INDEX ON Person(firstName)");
});
Console.WriteLine("Inserting a document");
// This is one way of creating Ion values. We can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));
driver.Execute(txn =>
{
txn.Execute("INSERT INTO Person ?", ionPerson);
});
Console.WriteLine("Querying the table");
IIonValue ionFirstName = valueFactory.NewString("John");
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult selectResult = driver.Execute(txn =>
{
return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});
foreach (IIonValue row in selectResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
Console.WriteLine("Updating a document");
IIonValue ionIntAge = valueFactory.NewInt(42);
IIonValue ionFirstName2 = valueFactory.NewString("John");
driver.Execute(txn =>
{
txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
});
Console.WriteLine("Querying the table for the updated document");
IIonValue ionFirstName3 = valueFactory.NewString("John");
IResult updateResult = driver.Execute(txn =>
{
return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
});
foreach (IIonValue row in updateResult)
{
Console.WriteLine(row.GetField("firstName").StringValue);
Console.WriteLine(row.GetField("lastName").StringValue);
Console.WriteLine(row.GetField("age").IntValue);
}
}
}
}
Para executar o aplicativo, insira o comando a seguir do diretório principal do seu diretório de projeto Amazon.QLDB.QuickStartGuide
.
$
dotnet run --project Amazon.QLDB.QuickStartGuide