Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Controlador de Amazon QLDB para .NET: tutorial de inicio rápido
En este tutorial aprenderá a configurar una aplicación sencilla con la versión más reciente del controlador de Amazon QLDB para .NET. En esta guía se incluyen los pasos para instalar el controlador y ejemplos de código breve de las operaciones básicas de creación, lectura, actualización y eliminación (CRUD).
Requisitos previos
Antes de comenzar, asegúrese de que hace lo siguiente:
Paso 1: Configuración del proyecto
En primer lugar, configure su proyecto de .NET.
-
Para crear y ejecutar una aplicación de plantilla, introduzca los siguientes dotnet
comandos en un terminal PowerShell, como bash o Command Prompt.
$
dotnet new console --output Amazon.QLDB.QuickStartGuide
$
dotnet run --project Amazon.QLDB.QuickStartGuide
Esta plantilla crea una carpeta llamada Amazon.QLDB.QuickStartGuide
. En esa carpeta, crea un proyecto con el mismo nombre y un archivo denominado Program.cs
. El programa contiene un código que muestra el resultado Hello World!
.
-
Utilice el administrador de NuGet paquetes para instalar el controlador QLDB para.NET. Recomendamos usar Visual Studio o el IDE de su elección para agregar dependencias a su proyecto. El nombre del paquete de controlador es Amazon.QLDB.Driver.
-
Por ejemplo, en Visual Studio, abra la consola NuGet Package Manager en el menú Herramientas. A continuación, ingrese el siguiente comando en el símbolo del sistema PM>
.
PM>
Install-Package Amazon.QLDB.Driver
-
O bien, puede ingresar los siguientes comandos en su terminal.
$
cd Amazon.QLDB.QuickStartGuide
$
dotnet add package Amazon.QLDB.Driver
Al instalar el controlador también se instalan sus dependencias, incluidos AWS SDK for .NET y las bibliotecas de Amazon Ion.
-
Instale la biblioteca de serialización del controlador.
PM>
Install-Package Amazon.QLDB.Driver.Serialization
-
Abra el archivo Program.cs
.
A continuación, añada gradualmente los ejemplos de código en los siguientes pasos para probar algunas operaciones básicas de CRUD. O bien, puede omitir el step-by-step tutorial y, en su lugar, ejecutar la aplicación completa.
-
Elegir entre síncrono y asíncrono APIs: el controlador proporciona funciones síncronas y asíncronas. APIs Para las aplicaciones de alta demanda que gestionan múltiples solicitudes sin bloquearlas, recomendamos utilizar las aplicaciones asíncronas para mejorar el rendimiento. APIs El controlador ofrece la función sincrónica APIs como una comodidad adicional para las bases de código existentes que se escriben de forma sincrónica.
Este tutorial incluye ejemplos de código síncrono y asíncrono. Para obtener más información sobre el APIs, consulte el IQldbcontrolador y las IAsyncQldbDriverinterfaces en la documentación de la API.
-
Procesamiento de los datos de Amazon Ion: en este tutorial, se proporcionan ejemplos de código sobre el procesamiento de datos de Amazon Ion mediante el mapeador de objetos Ion de forma predeterminada. QLDB introdujo el mapeador de objetos Ion en la versión 1.3.0 del controlador .NET. Cuando proceda, en este tutorial también se proporcionan ejemplos de código que utilizan la biblioteca Ion estándar como alternativa. Para obtener más información, consulte Trabajar con Amazon Ion.
Paso 2: inicializar el controlador
Inicialice una instancia del controlador que se conecte al libro mayor denominado quick-start
. Agregue el siguiente código al archivo 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();
}
}
}
Paso 3: crear una tabla y un índice
Para el resto de este tutorial hasta el paso 6, debe añadir los siguientes ejemplos de código al ejemplo de código anterior.
En este paso, el siguiente código muestra cómo ejecutar las instrucciones CREATE TABLE
y CREATE INDEX
. Este código crea una tabla con el nombre Person
y el índice para el campo firstName
de esa tabla. Los índices son necesarios para optimizar el rendimiento de las consultas y ayudar a limitar las excepciones de conflicto de control de concurrencia optimista (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)");
});
Paso 4: insertar un documento
El siguiente ejemplo de código muestra cómo ejecutar una instrucción INSERT
. QLDB es compatible con el lenguaje de consultas PartiQL (compatible con SQL) y el formato de datos Amazon Ion (superconjunto de JSON).
Añada el siguiente código para insertar un documento en la tabla 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 insertar varios documentos mediante una sola instrucción INSERT, puede pasar un parámetro del tipo Ion list a la instrucción de la siguiente manera.
// people is an Ion list
txn.Execute("INSERT INTO Person ?", people);
No coloque el marcador de posición variable (?
) entre corchetes de doble ángulo (<<...>>
) al pasar una lista Ion. En las instrucciones PartiQL manuales, los corchetes de doble ángulo indican una colección desordenada conocida como bolsa.
Paso 5: consulta del documento
El siguiente ejemplo de código muestra cómo ejecutar una instrucción SELECT
.
Agregue el siguiente código para consultar un documento de la tabla 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);
}
En este ejemplo se emplea un signo de interrogación (?
) como marcador de posición variable para pasar la información del documento a la instrucción. Al utilizar marcadores de posición, debe pasar un valor de tipo IonValue
.
Paso 6: actualizar el documento
El siguiente ejemplo de código muestra cómo ejecutar una instrucción UPDATE
.
-
Añada el siguiente código para actualizar un documento de la tabla Person
actualizando age
a 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);
});
-
Vuelva a consultar el documento para ver el valor actualizado.
- 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 ejecutar la aplicación, introduzca el siguiente comando desde el directorio principal del directorio del proyecto Amazon.QLDB.QuickStartGuide
.
$
dotnet run --project Amazon.QLDB.QuickStartGuide
-
Añada el siguiente código para actualizar un documento de la tabla Person
actualizando age
a 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);
});
-
Vuelva a consultar el documento para ver el valor actualizado.
- 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 ejecutar la aplicación, introduzca el siguiente comando desde el directorio principal del directorio del proyecto Amazon.QLDB.QuickStartGuide
.
$
dotnet run --project Amazon.QLDB.QuickStartGuide
Ejecución de la aplicación completa
El siguiente ejemplo de código es la versión completa de la aplicación Program.cs
. En lugar de seguir los pasos anteriores de forma individual, también puede copiar y ejecutar este ejemplo de código de principio a fin. Esta aplicación muestra algunas operaciones básicas de CRUD en el libro mayor denominado quick-start
.
Antes de ejecutar este código, asegúrese de no tener ya una tabla activa con el nombre Person
en el libro mayor 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 ejecutar la aplicación completa, introduzca el siguiente comando desde el directorio principal del directorio del proyecto Amazon.QLDB.QuickStartGuide
.
$
dotnet run --project Amazon.QLDB.QuickStartGuide