In this tutorial, we will write a program that interacts with Cassandra using an API of datastax instead of using CQL Shell as on the previous tutorial. We add the following dependency to the pom.xml file:

To connect with Cassandra, we first create a cluster object using Cluster.builder() and addContactPoint(). Then, we create a session with connect() method as follows:

Next, we use the same queries as presented on the tutorial Install and interact with Cassandra using CQL Shell and run these queries using execute() method. For example, we use the following code to delete a keySpace ( ‘IF EXISTS’ is used to avoid the error occured when the file does not exist):

Similarly, we can create a keySpace, create a table, insert data into a table, update table and extract data from a table as follows:

Run the above code, we get the following result:

We can also execute multiple modification statements (insert, update, delete) simultaneously using BATCH with following syntax:

Below is an example of using BATCH to insert data into emp table, update the table and delete a row in emp_city table :

So, we have finished writing a simple program that interacts with Cassandra using datastax’s API. The full code of this tutorial is provided below:

Note: the above program is written in Java but we can use Scala with the same syntax. A simplest way to do it is copying the code directly to a Scala Object, IntelliJ will automatically convert the code from Java to Scala for us.


January 15, 2019