Build a C# application

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe and are able to interact with it using the CQL shell. If not, please follow these steps in the quick start guide.
  • installed Visual Studio

Writing a HelloWorld C# app

In your Visual Studio create a new Project and choose Console Application as template. Follow the instructions to save the project.

Install YugaByteCassandraCSharpDriver C# driver

YugabyteDB has forked the Cassandra driver to add more features like JSONB and change the routing policy.Install the C# driver in your Visual Studio project byfollowing instructions on the page.

Copy the contents below to your Program.cs file.

  1. using System;
  2. using System.Linq;
  3. using Cassandra;
  4. namespace Yugabyte_CSharp_Demo
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. try
  11. {
  12. var cluster = Cluster.Builder()
  13. .AddContactPoints("127.0.0.1")
  14. .WithPort(9042)
  15. .Build();
  16. var session = cluster.Connect();
  17. session.Execute("CREATE KEYSPACE IF NOT EXISTS ybdemo");
  18. Console.WriteLine("Created keyspace ybdemo");
  19. var createStmt = "CREATE TABLE IF NOT EXISTS ybdemo.employee(" +
  20. "id int PRIMARY KEY, name varchar, age int, language varchar)";
  21. session.Execute(createStmt);
  22. Console.WriteLine("Created keyspace employee");
  23. var insertStmt = "INSERT INTO ybdemo.employee(id, name, age, language) " +
  24. "VALUES (1, 'John', 35, 'C#')";
  25. session.Execute(insertStmt);
  26. Console.WriteLine("Inserted data: {0}", insertStmt);
  27. var preparedStmt = session.Prepare("SELECT name, age, language " +
  28. "FROM ybdemo.employee WHERE id = ?");
  29. var selectStmt = preparedStmt.Bind(1);
  30. var result = session.Execute(selectStmt);
  31. var rows = result.GetRows().ToList();
  32. Console.WriteLine("Select query returned {0} rows", rows.Count());
  33. Console.WriteLine("Name\tAge\tLanguage");
  34. foreach (Row row in rows)
  35. Console.WriteLine("{0}\t{1}\t{2}", row["name"], row["age"], row["language"]);
  36. session.Dispose();
  37. cluster.Dispose();
  38. }
  39. catch (Cassandra.NoHostAvailableException)
  40. {
  41. Console.WriteLine("Make sure YugabyteDB is running locally!.");
  42. }
  43. catch (Cassandra.InvalidQueryException ie)
  44. {
  45. Console.WriteLine("Invalid Query: " + ie.Message);
  46. }
  47. }
  48. }
  49. }

Running the C# app

Run the C# app from menu select Run -> Start Without Debugging

You should see the following as the output.

  1. Created keyspace ybdemo
  2. Created keyspace employee
  3. Inserted data: INSERT INTO ybdemo.employee(id, name, age, language) VALUES (1, 'John', 35, 'C#')
  4. Select query returned 1 rows
  5. Name Age Language
  6. John 35 C#

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe, and are able to interact with it using the YSQL shell. If not, please follow these steps in the ysql guide.
  • installed Visual Studio

Writing a HelloWorld C# application

In your Visual Studio, create a new Project and choose Console Application as template. Follow the instructions to save the project.

Install YSQL C# driver

To install the driver in your Visual Studio project:

  • Open your Project Solution View.
  • Right-click on Packages and click Add Packages.Add Package
  • Search for Npgsql and click Add Package.Search Package

Copy the contents below to your Program.cs file

  1. using System;
  2. using Npgsql;
  3. namespace Yugabyte_CSharp_Demo
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. NpgsqlConnection conn = new NpgsqlConnection("host=localhost;port=5433;database=yb_demo;user id=yugabyte;password=");
  10. try
  11. {
  12. conn.Open();
  13. NpgsqlCommand empCreateCmd = new NpgsqlCommand("CREATE TABLE employee (id int PRIMARY KEY, name varchar, age int, language varchar);", conn);
  14. empCreateCmd.ExecuteNonQuery();
  15. Console.WriteLine("Created table Employee");
  16. NpgsqlCommand empInsertCmd = new NpgsqlCommand("INSERT INTO employee (id, name, age, language) VALUES (1, 'John', 35, 'CSharp');", conn);
  17. int numRows = empInsertCmd.ExecuteNonQuery();
  18. Console.WriteLine("Inserted data (1, 'John', 35, 'CSharp')");
  19. NpgsqlCommand empPrepCmd = new NpgsqlCommand("SELECT name, age, language FROM employee WHERE id = @EmployeeId", conn);
  20. empPrepCmd.Parameters.Add("@EmployeeId", NpgsqlTypes.NpgsqlDbType.Integer);
  21. empPrepCmd.Parameters["@EmployeeId"].Value = 1;
  22. NpgsqlDataReader reader = empPrepCmd.ExecuteReader();
  23. Console.WriteLine("Query returned:\nName\tAge\tLanguage");
  24. while (reader.Read())
  25. {
  26. Console.WriteLine("{0}\t{1}\t{2}", reader.GetString(0), reader.GetInt32(1), reader.GetString(2));
  27. }
  28. }
  29. catch (Exception ex)
  30. {
  31. Console.WriteLine("Failure: " + ex.Message);
  32. }
  33. finally
  34. {
  35. if (conn.State != System.Data.ConnectionState.Closed)
  36. {
  37. conn.Close();
  38. }
  39. }
  40. }
  41. }
  42. }

Running the C# application

Run the C# app from menu select Run -> Start Without Debugging

You should see the following as the output.

  1. Created table Employee
  2. Inserted data (1, 'John', 35, 'CSharp')
  3. Query returned:
  4. Name Age Language
  5. John 35 CSharp