Amazon QLDB Driver pour. NET— Tutoriel de démarrage rapide - Base de données Amazon Quantum Ledger (AmazonQLDB)

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Amazon QLDB Driver pour. NET— Tutoriel de démarrage rapide

Important

Avis de fin de support : les clients existants pourront utiliser Amazon QLDB jusqu'à la fin du support le 31 juillet 2025. Pour plus de détails, consultez Migrer un Amazon QLDB Ledger vers Amazon Aurora SQL Postgre.

Dans ce didacticiel, vous apprendrez à configurer une application simple à l'aide du QLDB pilote Amazon pour. NET. Ce guide inclut les étapes d'installation du pilote et des exemples de code abrégé des opérations de base de création, de lecture, de mise à jour et de suppression (CRUD).

Prérequis

Avant de commencer, assurez-vous d'effectuer les opérations suivantes :

  1. Complétez le Prérequis pour le. NETchauffeur, si vous ne l'avez pas déjà fait. Cela inclut l'inscription AWS, l'octroi d'un accès programmatique pour le développement et l'installation du. NETNoyauSDK.

  2. Créez un registre nomméquick-start.

    Pour savoir comment créer un registre, voir Opérations de base pour Amazon QLDB Ledgers ou Étape 1 : Création d'un nouveau registre dans Commencer à utiliser la console.

Étape 1 : Configurer votre projet

Tout d'abord, configurez votre. NETprojet.

  1. Pour créer et exécuter un modèle d'application, entrez les dotnet commandes suivantes sur un terminal tel que bash ou Command Prompt. PowerShell

    $ dotnet new console --output Amazon.QLDB.QuickStartGuide $ dotnet run --project Amazon.QLDB.QuickStartGuide

    Ce modèle crée un dossier nomméAmazon.QLDB.QuickStartGuide. Dans ce dossier, il crée un projet portant le même nom et un fichier nomméProgram.cs. Le programme contient du code qui affiche le résultatHello World!.

  2. Utilisez le gestionnaire de NuGet packages pour installer le QLDB pilote pour. NET. Nous vous recommandons d'utiliser Visual Studio ou un autre IDE de votre choix pour ajouter des dépendances à votre projet. Le nom du package de pilotes est Amazon. QLDB.Chauffeur.

    • Par exemple, dans Visual Studio, ouvrez la console NuGet Package Manager dans le menu Outils. Entrez ensuite la commande suivante à l'PM>invite.

      PM> Install-Package Amazon.QLDB.Driver
    • Vous pouvez également saisir les commandes suivantes sur votre terminal.

      $ cd Amazon.QLDB.QuickStartGuide $ dotnet add package Amazon.QLDB.Driver

    L'installation du pilote installe également ses dépendances, notamment les bibliothèques AWS SDK for .NETet Amazon Ion.

  3. Installez la bibliothèque de sérialisation du pilote.

    PM> Install-Package Amazon.QLDB.Driver.Serialization
  4. Ouvrez le fichier Program.cs.

    Ajoutez ensuite progressivement les exemples de code dans les étapes suivantes pour essayer certaines CRUD opérations de base. Vous pouvez également ignorer le step-by-step didacticiel et exécuter l'application complète à la place.

Note
  • Choix entre synchrone et asynchrone APIs : le pilote fournit des options synchrone et asynchrone. APIs Pour les applications très demandées qui traitent plusieurs demandes sans les bloquer, nous recommandons d'utiliser le mode asynchrone APIs pour améliorer les performances. Le pilote offre le mode synchrone APIs pour une commodité supplémentaire pour les bases de code existantes qui sont écrites de manière synchrone.

    Ce didacticiel inclut des exemples de code synchrone et asynchrone. Pour plus d'informations à ce sujetAPIs, consultez les IAsyncQldbDriverinterfaces IQldbDriveret dans la API documentation.

  • Traitement des données Amazon Ion : ce didacticiel fournit des exemples de code relatifs au traitement des données Amazon Ion à l'aide du mappeur d'objets Ion par défaut. QLDBa introduit le mappeur d'objets Ion dans la version 1.3.0 du. NETchauffeur. Le cas échéant, ce didacticiel fournit également des exemples de code utilisant la bibliothèque Ion standard comme alternative. Pour en savoir plus, veuillez consulter la section Travailler avec Amazon Ion.

Étape 2 : Initialisation du pilote

Initialisez une instance du pilote qui se connecte au registre nommé. quick-start Ajoutez le code suivant à votre Program.cs fichier.

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(); } } }

Étape 3 : Création d'une table et d'un index

Pour le reste de ce didacticiel, jusqu'à l'étape 6, vous devez ajouter les exemples de code suivants à l'exemple de code précédent.

Au cours de cette étape, le code suivant montre comment exécuter CREATE TABLE des CREATE INDEX instructions. Il crée une table nommée Person et un index pour le firstName champ de cette table. Les index sont nécessaires pour optimiser les performances des requêtes et aider à limiter les exceptions de conflit optimistes en matière de contrôle de simultanéité (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)"); });

Étape 4 : Insérer un document

L'exemple de code suivant montre comment exécuter une INSERT instruction. QLDBprend en charge le langage de requête partiQL (SQLcompatible) et le format de données Amazon Ion (surensemble de). JSON

Ajoutez le code suivant qui insère un document dans le Person tableau.

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); });
Astuce

Pour insérer plusieurs documents à l'aide d'une seule INSERT instruction, vous pouvez transmettre un paramètre de type liste d'ions à l'instruction comme suit.

// people is an Ion list txn.Execute("INSERT INTO Person ?", people);

Vous ne placez pas la variable placeholder (?) entre crochets (<<...>>) lorsque vous transmettez une liste d'ions. Dans les instructions partiQL manuelles, les crochets à double angle indiquent une collection non ordonnée appelée sac.

Étape 5 : Interrogez le document

L'exemple de code suivant montre comment exécuter une SELECT instruction.

Ajoutez le code suivant qui interroge un document à partir de la Person table.

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); }

Cet exemple utilise un point d'interrogation (?) comme espace réservé aux variables pour transmettre les informations du document à l'instruction. Lorsque vous utilisez des espaces réservés, vous devez transmettre une valeur de typeIonValue.

Étape 6 : Mettre à jour le document

L'exemple de code suivant montre comment exécuter une UPDATE instruction.

  1. Ajoutez le code suivant qui met à jour un document dans le Person tableau en le mettant à jour age vers 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); });
  2. Interrogez à nouveau le document pour voir la valeur mise à jour.

    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 }
  3. Pour exécuter l'application, entrez la commande suivante depuis le répertoire parent du répertoire de votre Amazon.QLDB.QuickStartGuide projet.

    $ dotnet run --project Amazon.QLDB.QuickStartGuide
  1. Ajoutez le code suivant qui met à jour un document dans le Person tableau en le mettant à jour age vers 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); });
  2. Interrogez à nouveau le document pour voir la valeur mise à jour.

    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); }
  3. Pour exécuter l'application, entrez la commande suivante depuis le répertoire parent du répertoire de votre Amazon.QLDB.QuickStartGuide projet.

    $ dotnet run --project Amazon.QLDB.QuickStartGuide

Exécution de l'application complète

L'exemple de code suivant représente la version complète de l'Program.csapplication. Au lieu d'effectuer les étapes précédentes individuellement, vous pouvez également copier et exécuter cet exemple de code du début à la fin. Cette application montre certaines CRUD opérations de base sur le registre nomméquick-start.

Note

Avant d'exécuter ce code, assurez-vous qu'aucune table active n'est déjà nommée Person dans le quick-start registre.

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); } } } }

Pour exécuter l'application complète, entrez la commande suivante depuis le répertoire parent du répertoire de votre Amazon.QLDB.QuickStartGuide projet.

$ dotnet run --project Amazon.QLDB.QuickStartGuide