DataStax C# driver
Before using a DataStax driver, review Best practices for DataStax drivers and upgrade or install the latest supported driver for your language. For more details about supported software, see the DataStax Support Policy.
Upgrade your driver to a compatible version to connect to Astra DB databases. For more information, see the DataStax Driver Matrix. |
Connect the C# driver
-
Create a database, and then set environment variables for database ID, region, and keyspace.
-
Create an application token, and then set a token environment variable.
The
token.json
has the following format:{ "clientId": "CLIENT_ID", "secret": "CLIENT_SECRET", "token": "APPLICATION_TOKEN" }
For authentication with the driver, you can use either
clientId
andsecret
or the literal stringtoken
and theAstraCS
token value. If you are on an older driver version that doesn’t supporttoken
andAstraCS
, then you might need to useclientId
andsecret
. -
Download your database’s Secure Connect Bundle (SCB).
-
Download and install the current version of the Microsoft .NET Core SDK.
-
Create a new C# project and configure it to connect to your Astra DB database:
mkdir csharpproject cd csharpproject dotnet new console
-
Add the dependencies for the latest C# driver to your project:
dotnet add package CassandraCSharpDriver -v <version>
-
Replace the code in
Program.cs
with the following code to connect to your Astra DB database.Include the absolute path to the Secure Connect Bundle (SCB) for your Astra DB database (
secure-connect-DATABASE_NAME.zip
) in theWithCloudSecureConnectionBundle
method call, and your credentials in theWithCredentials
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() .WithCloudSecureConnectionBundle(@"C:PATH_TO_SCB") .WithCredentials("clientId", "clientSecret") .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