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.
using System;
using System.Linq;
using Cassandra;
namespace Yugabyte_CSharp_Demo
{
class Program
{
static void Main(string[] args)
{
try
{
var cluster = Cluster.Builder()
.AddContactPoints("127.0.0.1")
.WithPort(9042)
.Build();
var session = cluster.Connect();
session.Execute("CREATE KEYSPACE IF NOT EXISTS ybdemo");
Console.WriteLine("Created keyspace ybdemo");
var createStmt = "CREATE TABLE IF NOT EXISTS ybdemo.employee(" +
"id int PRIMARY KEY, name varchar, age int, language varchar)";
session.Execute(createStmt);
Console.WriteLine("Created keyspace employee");
var insertStmt = "INSERT INTO ybdemo.employee(id, name, age, language) " +
"VALUES (1, 'John', 35, 'C#')";
session.Execute(insertStmt);
Console.WriteLine("Inserted data: {0}", insertStmt);
var preparedStmt = session.Prepare("SELECT name, age, language " +
"FROM ybdemo.employee WHERE id = ?");
var selectStmt = preparedStmt.Bind(1);
var result = session.Execute(selectStmt);
var rows = result.GetRows().ToList();
Console.WriteLine("Select query returned {0} rows", rows.Count());
Console.WriteLine("Name\tAge\tLanguage");
foreach (Row row in rows)
Console.WriteLine("{0}\t{1}\t{2}", row["name"], row["age"], row["language"]);
session.Dispose();
cluster.Dispose();
}
catch (Cassandra.NoHostAvailableException)
{
Console.WriteLine("Make sure YugabyteDB is running locally!.");
}
catch (Cassandra.InvalidQueryException ie)
{
Console.WriteLine("Invalid Query: " + ie.Message);
}
}
}
}
Running the C# app
Run the C# app from menu select Run -> Start Without Debugging
You should see the following as the output.
Created keyspace ybdemo
Created keyspace employee
Inserted data: INSERT INTO ybdemo.employee(id, name, age, language) VALUES (1, 'John', 35, 'C#')
Select query returned 1 rows
Name Age Language
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.
- Search for Npgsql and click Add Package.
Copy the contents below to your Program.cs file
using System;
using Npgsql;
namespace Yugabyte_CSharp_Demo
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection conn = new NpgsqlConnection("host=localhost;port=5433;database=yb_demo;user id=yugabyte;password=");
try
{
conn.Open();
NpgsqlCommand empCreateCmd = new NpgsqlCommand("CREATE TABLE employee (id int PRIMARY KEY, name varchar, age int, language varchar);", conn);
empCreateCmd.ExecuteNonQuery();
Console.WriteLine("Created table Employee");
NpgsqlCommand empInsertCmd = new NpgsqlCommand("INSERT INTO employee (id, name, age, language) VALUES (1, 'John', 35, 'CSharp');", conn);
int numRows = empInsertCmd.ExecuteNonQuery();
Console.WriteLine("Inserted data (1, 'John', 35, 'CSharp')");
NpgsqlCommand empPrepCmd = new NpgsqlCommand("SELECT name, age, language FROM employee WHERE id = @EmployeeId", conn);
empPrepCmd.Parameters.Add("@EmployeeId", NpgsqlTypes.NpgsqlDbType.Integer);
empPrepCmd.Parameters["@EmployeeId"].Value = 1;
NpgsqlDataReader reader = empPrepCmd.ExecuteReader();
Console.WriteLine("Query returned:\nName\tAge\tLanguage");
while (reader.Read())
{
Console.WriteLine("{0}\t{1}\t{2}", reader.GetString(0), reader.GetInt32(1), reader.GetString(2));
}
}
catch (Exception ex)
{
Console.WriteLine("Failure: " + ex.Message);
}
finally
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}
}
}
}
Running the C# application
Run the C# app from menu select Run -> Start Without Debugging
You should see the following as the output.
Created table Employee
Inserted data (1, 'John', 35, 'CSharp')
Query returned:
Name Age Language
John 35 CSharp