Skip to content

Instantly share code, notes, and snippets.

@beccam
Last active August 6, 2020 14:09
Show Gist options
  • Save beccam/7a53320a9aa28d83f7502ce5150d8993 to your computer and use it in GitHub Desktop.
Save beccam/7a53320a9aa28d83f7502ce5150d8993 to your computer and use it in GitHub Desktop.
Connect to Astra with the DataStax C# driver
using Cassandra;
using System.Linq;
using System;
namespace QuickStart
{
class AstraConnect
{
static void Main(string[] args)
{
Cluster cluster = Cluster.Builder()
.WithCloudSecureConnectionBundle(@"C:\path\to\secure-connect-database_name.zip")
.WithCredentials("username", "password")
.Build();
ISession session = cluster.Connect("demo");
var statement = new SimpleStatement("CREATE TABLE IF NOT EXISTS demo.users ("
+ " lastname text PRIMARY KEY,"
+ " age int,"
+ " city text,"
+ " email text," +
" firstname text)");
session.Execute(statement);
SetUser(session, "Jones", 35, "Austin", "bob@example.com", "Bob");
GetUser(session, "Jones");
UpdateUser(session, 36, "Jones");
GetUser(session, "Jones");
DeleteUser(session, "Jones");
cluster.Dispose();
}
private static void SetUser(ISession session, String lastname, int age, String city, String email, String firstname)
{
//TO DO: execute SimpleStatement that inserts one user into the table
var statement = new SimpleStatement("INSERT INTO users (lastname, age, city, email, firstname) VALUES (?,?,?,?,?)", lastname, age, city, email, firstname);
session.Execute(statement);
}
private static void GetUser(ISession session, String lastname)
{
//TO DO: execute SimpleStatement that retrieves one user from the table
//TO DO: print firstname and age of user
var statement = new SimpleStatement("SELECT * FROM users WHERE lastname = :lastname", lastname);
var result = session.Execute(statement).First();
Console.WriteLine("{0} {1}", result["firstname"], result["age"]);
}
private static void UpdateUser(ISession session, int age, String lastname)
{
//TO DO: execute PreparedStatement that updates the age of one user
PreparedStatement prepared = session.Prepare("UPDATE users SET age =? WHERE lastname = ?");
BoundStatement bound = prepared.Bind(age, lastname);
session.Execute(bound);
}
private static void DeleteUser(ISession session, String lastname)
{
PreparedStatement prepared = session.Prepare("DELETE FROM users WHERE lastname = ?");
BoundStatement bound = prepared.Bind(lastname);
session.Execute(bound);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment