Join us on
Star us on
Get Started
Slack
GitHub
Get Started
v2.5 (latest) v2.2 (stable) v2.1 (earlier version) v2.0 (earlier version) v1.3 (earlier version)
  • GET STARTED
    • Quick start
      • 1. Install YugabyteDB
      • 2. Create a local cluster
      • 3. Explore YSQL
      • 4. Build an application
        • Java
        • NodeJS
        • Go
        • Python
        • Ruby
        • C#
        • PHP
        • C++
        • C
    • Introduction
    • Explore core
      • 1. Linear scalability
      • 2. Fault tolerance
      • 3. Global distribution
      • 4. Auto sharding
      • 5. Tunable reads
      • 6. Observability
  • USER GUIDES
    • Develop
      • Learn app development
        • 1. SQL vs NoSQL
        • 2. Data modeling
        • 3. Data types
        • 4. ACID transactions
        • 5. Aggregations
        • 6. Batch operations
        • 7. Date and time
        • 8. Strings and text
      • Ecosystem integrations
        • Apache Kafka
        • Apache Spark
        • JanusGraph
        • KairosDB
        • Presto
        • Metabase
      • Real-world examples
        • E-Commerce App
        • IoT Fleet Management
        • Retail Analytics
      • Explore sample applications
    • Deploy
      • Checklist
      • Manual deployment
        • 1. System configuration
        • 2. Install software
        • 3. Start YB-Masters
        • 4. Start YB-TServers
        • 5. Verify deployment
      • Kubernetes
        • Helm Chart
        • Helm configuration
        • Local SSD
      • Docker
      • Public clouds
        • Amazon Web Services
        • Google Cloud Platform
        • Microsoft Azure
      • Pivotal Cloud Foundry
      • Yugabyte Platform
        • 1. Prepare cloud environment
        • 2. Install Admin Console
        • 3. Configure Admin Console
        • 4. Configure Cloud Providers
    • Benchmark
      • Performance
      • YCSB
      • Large datasets
    • Secure
      • Security checklist
      • Authentication
      • Authorization
        • 1. RBAC Model
        • 2. Create Roles
        • 3. Grant permissions
      • TLS encryption
        • 1. Prepare nodes
        • 2. Server-server encryption
        • 3. Client-server encryption
        • 4. Connect to cluster
      • Encryption at Rest
    • Manage
      • Backup and restore
        • Backing up data
        • Restoring data
      • Data migration
        • Bulk import
        • Bulk export
      • Change cluster config
      • Upgrade deployment
      • Diagnostics reporting
      • Yugabyte Platform
        • Create universe - Multi-zone
        • Create universe - Multi-region
        • Edit universe
        • Edit config flags
        • Health checking and alerts
        • Create and edit instance tags
        • Node status and actions
        • Read replicas
        • Back up and restore
        • Upgrade universe
        • Delete universe
    • Troubleshoot
      • Troubleshooting overview
      • Cluster level issues
        • YCQL connection issues
        • YEDIS connection Issues
      • Node level issues
        • Check processes
        • Inspect logs
        • System statistics
      • Yugabyte Platform
        • Troubleshoot universes
  • REFERENCE
    • APIs
      • YSQL
        • Statements
          • ABORT
          • ALTER DATABASE
          • ALTER DOMAIN
          • ALTER TABLE
          • BEGIN
          • COMMENT
          • COMMIT
          • COPY
          • CREATE DATABASE
          • CREATE DOMAIN
          • CREATE INDEX
          • CREATE SCHEMA
          • CREATE SEQUENCE
          • CREATE TABLE
          • CREATE TABLE AS
          • CREATE TYPE
          • CREATE USER
          • CREATE VIEW
          • DEALLOCATE
          • DELETE
          • DROP DATABASE
          • DROP DOMAIN
          • DROP SEQUENCE
          • DROP TABLE
          • DROP TYPE
          • END
          • EXECUTE
          • EXPLAIN
          • GRANT
          • INSERT
          • LOCK
          • PREPARE
          • RESET
          • REVOKE
          • ROLLBACK
          • SELECT
          • SET
          • SET CONSTRAINTS
          • SET TRANSACTION
          • SHOW
          • SHOW TRANSACTION
          • TRUNCATE
          • UPDATE
        • Data types
          • Binary
          • Boolean
          • Character
          • Date-time
          • Json
          • Money
          • Numeric
          • Serial
          • UUID
        • Expressions
          • currval()
          • lastval()
          • nextval()
        • Keywords
        • Reserved Names
      • YCQL
        • Quick Start YCQL
        • ALTER KEYSPACE
        • ALTER ROLE
        • ALTER TABLE
        • CREATE INDEX
        • CREATE KEYSPACE
        • CREATE ROLE
        • CREATE TABLE
        • CREATE TYPE
        • DROP INDEX
        • DROP KEYSPACE
        • DROP ROLE
        • DROP TABLE
        • DROP TYPE
        • GRANT PERMISSION
        • GRANT ROLE
        • REVOKE PERMISSION
        • REVOKE ROLE
        • USE
        • INSERT
        • SELECT
        • UPDATE
        • DELETE
        • TRANSACTION
        • TRUNCATE
        • Simple Value
        • Subscript
        • Function Call
        • Operator Call
        • BLOB
        • BOOLEAN
        • MAP, SET, LIST
        • FROZEN
        • INET
        • Integer & Counter
        • Non-Integer
        • TEXT
        • Date & Time Types
        • UUID & TIMEUUID
        • JSONB
        • Date and time functions
    • CLIs
      • yb-ctl
      • yb-docker-ctl
      • yb-master
      • yb-tserver
      • ysqlsh
      • cqlsh
    • Sample data
      • Chinook
      • Northwind
      • PgExercises
      • SportsDB
    • Tools
      • TablePlus
  • RELEASES
    • Release history
      • v1.3.1
      • v1.3.0
      • v1.2.12
      • v1.2.11
      • v1.2.10
      • v1.2.9
      • v1.2.8
      • v1.2.6
      • v1.2.5
      • v1.2.4
  • CONCEPTS
    • Architecture
      • Design goals
      • Layered architecture
      • Basic concepts
        • Universe
        • YB-TServer
        • YB-Master
        • Acknowledgements
      • Query layer
        • Overview
      • DocDB store
        • Sharding
        • Replication
        • Persistence
        • Performance
      • DocDB transactions
        • Isolation Levels
        • Single row transactions
        • Distributed transactions
        • Transactional IO path
  • FAQ
    • Comparisons
      • CockroachDB
      • Google Cloud Spanner
      • MongoDB
      • FoundationDB
      • Amazon DynamoDB
      • Azure Cosmos DB
      • Apache Cassandra
      • Redis in-memory store
      • Apache HBase
    • Other FAQs
      • Product
      • Architecture
      • Yugabyte Platform
      • API compatibility
  • CONTRIBUTOR GUIDES
    • Get involved
  • Misc
    • YEDIS
      • Quick start
      • Develop
        • Client drivers
          • C
          • C++
          • C#
          • Go
          • Java
          • NodeJS
          • Python
      • API reference
        • APPEND
        • AUTH
        • CONFIG
        • CREATEDB
        • DELETEDB
        • LISTDB
        • SELECT
        • DEL
        • ECHO
        • EXISTS
        • EXPIRE
        • EXPIREAT
        • FLUSHALL
        • FLUSHDB
        • GET
        • GETRANGE
        • GETSET
        • HDEL
        • HEXISTS
        • HGET
        • HGETALL
        • HINCRBY
        • HKEYS
        • HLEN
        • HMGET
        • HMSET
        • HSET
        • HSTRLEN
        • HVALS
        • INCR
        • INCRBY
        • KEYS
        • MONITOR
        • PEXPIRE
        • PEXPIREAT
        • PTTL
        • ROLE
        • SADD
        • SCARD
        • RENAME
        • SET
        • SETEX
        • PSETEX
        • SETRANGE
        • SISMEMBER
        • SMEMBERS
        • SREM
        • STRLEN
        • ZRANGE
        • TSADD
        • TSCARD
        • TSGET
        • TSLASTN
        • TSRANGEBYTIME
        • TSREM
        • TSREVRANGEBYTIME
        • TTL
        • ZADD
        • ZCARD
        • ZRANGEBYSCORE
        • ZREM
        • ZREVRANGE
        • ZSCORE
        • PUBSUB
        • PUBLISH
        • SUBSCRIBE
        • UNSUBSCRIBE
        • PSUBSCRIBE
        • PUNSUBSCRIBE
> Quick start > 4. Build an application >

C#

Attention

This page documents an earlier version. Go to the latest (v2.3) version.
  • YCQL
  • YSQL

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 Cassandra C# driver

To install the driver in your Visual Studio project

  1. Open your Project Solution View.
  2. Right-click on Packages and click Add Packages.
  3. Search for CassandraCSharpDriver and click Add Package.

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

            <span style="color:#b00040">var</span> createStmt = <span style="color:#ba2121">&#34;CREATE TABLE IF NOT EXISTS ybdemo.employee(&#34;</span> +
                <span style="color:#ba2121">&#34;id int PRIMARY KEY, name varchar, age int, language varchar)&#34;</span>;
            session.Execute(createStmt);
            Console.WriteLine(<span style="color:#ba2121">&#34;Created keyspace employee&#34;</span>);

            <span style="color:#b00040">var</span> insertStmt = <span style="color:#ba2121">&#34;INSERT INTO ybdemo.employee(id, name, age, language) &#34;</span> +
                <span style="color:#ba2121">&#34;VALUES (1, &#39;John&#39;, 35, &#39;C#&#39;)&#34;</span>;
            session.Execute(insertStmt);
            Console.WriteLine(<span style="color:#ba2121">&#34;Inserted data: {0}&#34;</span>, insertStmt);

            <span style="color:#b00040">var</span> preparedStmt = session.Prepare(<span style="color:#ba2121">&#34;SELECT name, age, language &#34;</span> +
                                               <span style="color:#ba2121">&#34;FROM ybdemo.employee WHERE id = ?&#34;</span>);
            <span style="color:#b00040">var</span> selectStmt = preparedStmt.Bind(<span style="color:#666">1</span>);
            <span style="color:#b00040">var</span> result = session.Execute(selectStmt);
            <span style="color:#b00040">var</span> rows = result.GetRows().ToList();
            Console.WriteLine(<span style="color:#ba2121">&#34;Select query returned {0} rows&#34;</span>, rows.Count());
            Console.WriteLine(<span style="color:#ba2121">&#34;Name\tAge\tLanguage&#34;</span>);
            <span style="color:#008000;font-weight:bold">foreach</span> (Row row <span style="color:#008000;font-weight:bold">in</span> rows)
                Console.WriteLine(<span style="color:#ba2121">&#34;{0}\t{1}\t{2}&#34;</span>, row[<span style="color:#ba2121">&#34;name&#34;</span>], row[<span style="color:#ba2121">&#34;age&#34;</span>], row[<span style="color:#ba2121">&#34;language&#34;</span>]);

            session.Dispose();
            cluster.Dispose();

        }
        <span style="color:#008000;font-weight:bold">catch</span> (Cassandra.NoHostAvailableException)
        {
            Console.WriteLine(<span style="color:#ba2121">&#34;Make sure YugabyteDB is running locally!.&#34;</span>);
        }
        <span style="color:#008000;font-weight:bold">catch</span> (Cassandra.InvalidQueryException ie)
        {
            Console.WriteLine(<span style="color:#ba2121">&#34;Invalid Query: &#34;</span> + 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

  1. Open your Project Solution View.
  2. Right-click on Packages and click Add Packages.
  3. 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=postgres;password=");

        <span style="color:#008000;font-weight:bold">try</span>
        {
            conn.Open();

            NpgsqlCommand empCreateCmd = <span style="color:#008000;font-weight:bold">new</span> NpgsqlCommand(<span style="color:#ba2121">&#34;CREATE TABLE employee (id int PRIMARY KEY, name varchar, age int, language varchar);&#34;</span>, conn);
            empCreateCmd.ExecuteNonQuery();
            Console.WriteLine(<span style="color:#ba2121">&#34;Created table Employee&#34;</span>);

            NpgsqlCommand empInsertCmd = <span style="color:#008000;font-weight:bold">new</span> NpgsqlCommand(<span style="color:#ba2121">&#34;INSERT INTO employee (id, name, age, language) VALUES (1, &#39;John&#39;, 35, &#39;CSharp&#39;);&#34;</span>, conn);
            <span style="color:#b00040">int</span> numRows = empInsertCmd.ExecuteNonQuery();
            Console.WriteLine(<span style="color:#ba2121">&#34;Inserted data (1, &#39;John&#39;, 35, &#39;CSharp&#39;)&#34;</span>);

            NpgsqlCommand empPrepCmd = <span style="color:#008000;font-weight:bold">new</span> NpgsqlCommand(<span style="color:#ba2121">&#34;SELECT name, age, language FROM employee WHERE id = @EmployeeId&#34;</span>, conn);
            empPrepCmd.Parameters.Add(<span style="color:#ba2121">&#34;@EmployeeId&#34;</span>, NpgsqlTypes.NpgsqlDbType.Integer);

            empPrepCmd.Parameters[<span style="color:#ba2121">&#34;@EmployeeId&#34;</span>].Value = <span style="color:#666">1</span>;
            NpgsqlDataReader reader = empPrepCmd.ExecuteReader();

            Console.WriteLine(<span style="color:#ba2121">&#34;Query returned:\nName\tAge\tLanguage&#34;</span>); 
            <span style="color:#008000;font-weight:bold">while</span> (reader.Read())
            {
                Console.WriteLine(<span style="color:#ba2121">&#34;{0}\t{1}\t{2}&#34;</span>, reader.GetString(<span style="color:#666">0</span>), reader.GetInt32(<span style="color:#666">1</span>), reader.GetString(<span style="color:#666">2</span>));
            }
        }
        <span style="color:#008000;font-weight:bold">catch</span> (Exception ex)
        {
            Console.WriteLine(<span style="color:#ba2121">&#34;Failure: &#34;</span> + ex.Message);
        }
        <span style="color:#008000;font-weight:bold">finally</span>
        {
            <span style="color:#008000;font-weight:bold">if</span> (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
Ask our community
  • Slack
  • Github
  • Forum
  • StackOverflow
Yugabyte
Contact Us
Copyright © 2017-2020 Yugabyte, Inc. All rights reserved.