Connect with the C# driver
This guide provides an end-to-end workflow for how to install the driver, connect it to your database, and migrate an existing DataStax C# driver to a version that is capable of connecting to your HCD database.
Prerequisites
-
Install a cluster and start HCD
-
Install C#.
-
Install the latest .NET SDK
HCD APIs use the term keyspace to refer to both namespaces and keyspaces. |
Install the C# driver
The C# driver is available as a NuGet package and can be installed using the .NET CLI or Visual Studio Package Manager.
Use the .NET CLI
dotnet add package CassandraCSharpDriver
Use the Package Manager Console
Install-Package CassandraCSharpDriver
Use PackageReference
Add the following to your .csproj
file:
<PackageReference Include="CassandraCSharpDriver" Version="3.18.0" />
Replace |
Connect to your database
-
Create a new C# project and configure it to connect to your Cassandra database.
mkdir csharpproject cd csharpproject dotnet new console
-
Add a dependency for the C# driver
:
dotnet add package CassandraCSharpDriver -v <version>
-
Replace the code in
Program.cs
with the following code to connect to your HCD database.Include your credentials in the
WithCredentials
method call, as shown in the following examples.using System; using System.Linq; using Cassandra; namespace csharpproject { class Program { static void Main(string[] args) { var session = Cluster.Builder() .WithCredentials("username", "password") .Build() .Connect(); } } }
-
After the connection code, add the following code to the
Main
method inProgram.cs
. This code runs a CQL query and prints the output to the console.var rowSet = session.Execute("select * from system.local"); Console.WriteLine(rowSet.First().GetValue<string>("cluster_name"));
-
Run your C# project with the
dotnet
runtime.dotnet restore dotnet build dotnet run --no-build