Illustration Image

Cassandra.Link

The best knowledge base on Apache Cassandra®

Helping platform leaders, architects, engineers, and operators build scalable real time data platforms.

10/23/2020

Reading time:2 min

DataStax-Examples/quickstart-csharp

by DataStax-Examples

A basic C#/.NET demo CRUD application using the DataStax C# Driver for Apache Cassandra.Use the QuickStartComplete project if you want to skip the exercise and run the application with the complete code.Contributors: Rebecca MillsObjectivesTo demonstrate how to perform basic CRUD operations with the DataStax C# Driver.The intent is to help users get up and running quickly with the driver.How this Sample WorksThis project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.Project LayoutProgram.cs - C# application file with space to fill in CRUD operation codeQuickStart.csproj - Visual Studio .NET C# Project fileusers.cql - Use this file to create the schemaPrerequisitesA running instance of Apache Cassandra® 1.2+Mircosoft Visual Studio with .NET Core 2.1+IDE Alternatives: Visual Studio Code or RiderCreate the keyspace and tableThe users.cql file provides the schema used for this project:CREATE KEYSPACE demo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};CREATE TABLE demo.users ( lastname text PRIMARY KEY, age int, city text, email text, firstname text);Connect to your clusterAll of our code is contained in the Program class.Note how the main method creates a session to connect to our cluster and runs the CRUD operations against it.Replace the default parameter in Cluster.Builder() with your own contact point.// TO DO: Fill in your own contact pointCluster cluster = Cluster.Builder() .AddContactPoint("127.0.0.1") .Build();ISession session = cluster.Connect("demo");CRUD OperationsFill the code in the methods that will add a user, get a user, update a user and delete a user from the table with the driver.INSERT a userprivate 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);}SELECT a user 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); var result = session.Execute(statement).First(); Console.WriteLine("{0} {1}", result["firstname"], result["age"]);}UPDATE a user's ageprivate static void UpdateUser(ISession session, int age, String lastname) { //TO DO: execute SimpleStatement that updates the age of one user var statement = new SimpleStatement("UPDATE users SET age =? WHERE lastname = ?", age, lastname); session.Execute(statement);}DELETE a userprivate static void DeleteUser(ISession session, String lastname) { //TO DO: execute SimpleStatement that deletes one user from the table var statement = new SimpleStatement("DELETE FROM users WHERE lastname = ?", lastname); session.Execute(statement);}LicenseCopyright 2019 Rebecca MillsLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

Illustration Image

Build Status

A basic C#/.NET demo CRUD application using the DataStax C# Driver for Apache Cassandra. Use the QuickStartComplete project if you want to skip the exercise and run the application with the complete code.

Contributors: Rebecca Mills

Objectives

  • To demonstrate how to perform basic CRUD operations with the DataStax C# Driver.
  • The intent is to help users get up and running quickly with the driver.

How this Sample Works

This project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.

Project Layout

Prerequisites

Create the keyspace and table

The users.cql file provides the schema used for this project:

CREATE KEYSPACE demo
    WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
CREATE TABLE demo.users (
    lastname text PRIMARY KEY,
    age int,
    city text,
    email text,
    firstname text);

Connect to your cluster

All of our code is contained in the Program class. Note how the main method creates a session to connect to our cluster and runs the CRUD operations against it. Replace the default parameter in Cluster.Builder() with your own contact point.

// TO DO: Fill in your own contact point
Cluster cluster = Cluster.Builder()
                         .AddContactPoint("127.0.0.1")
                         .Build();
ISession session = cluster.Connect("demo");

CRUD Operations

Fill the code in the methods that will add a user, get a user, update a user and delete a user from the table with the driver.

INSERT a user

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

SELECT a user

 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);
      
      var result = session.Execute(statement).First();
      Console.WriteLine("{0} {1}", result["firstname"], result["age"]);
}

UPDATE a user's age

private static void UpdateUser(ISession session, int age, String lastname) {
    //TO DO: execute SimpleStatement that updates the age of one user
    var statement = new SimpleStatement("UPDATE users SET age =? WHERE lastname = ?", age, lastname);
    session.Execute(statement);
}

DELETE a user

private static void DeleteUser(ISession session, String lastname) {
    //TO DO: execute SimpleStatement that deletes one user from the table
    var statement = new SimpleStatement("DELETE FROM users WHERE lastname = ?", lastname);
    session.Execute(statement);
}

License

Copyright 2019 Rebecca Mills

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Related Articles

examples
cassandra
datastax

GitHub - datastaxdevs/workshop-betterreads: Clone of Good Reads using Spring and Cassandra

datastaxdevs

12/2/2023

Checkout Planet Cassandra

Claim Your Free Planet Cassandra Contributor T-shirt!

Make your contribution and score a FREE Planet Cassandra Contributor T-Shirt! 
We value our incredible Cassandra community, and we want to express our gratitude by sending an exclusive Planet Cassandra Contributor T-Shirt you can wear with pride.

Join Our Newsletter!

Sign up below to receive email updates and see what's going on with our company

Explore Related Topics

AllKafkaSparkScyllaSStableKubernetesApiGithubGraphQl

Explore Further

csharp