How to Connect to Cassandra DB from Java
07.05.2025
Connecting to Cassandra DB from Java can be a crucial task for many developers. In this article, we will discuss the steps to establish a connection to Cassandra DB from a Java application.

Setting up Cassandra Driver
In order to connect to Cassandra from Java, you need to include the DataStax Java Driver for Apache Cassandra in your project. You can add the driver as a Maven dependency in your project’s pom.xml file:
```xml com.datastax.cassandra java-driver-core 4.13.0 ```
Creating a Connection
Once you have included the Cassandra driver in your project, you can create a connection to Cassandra by following these steps:
- Create a Cluster: Use the Cluster.builder() method to create a Cluster object.
- Specify Contact Points: Set the contact points (IP addresses) of the Cassandra nodes in the cluster.
- Build the Cluster: Call the build() method on the Cluster object to establish the connection.
Creating a Session
After establishing a connection to the Cassandra cluster, you need to create a session to interact with the database. Follow these steps to create a session:
- Open a Session: Use the connect() method on the Cluster object to open a session.
- Execute Queries: You can now execute CQL queries using the session object.
Executing Queries
Once you have a session object, you can execute queries against the Cassandra database. Here is an example of how you can insert data into a table:
```java String insertQuery = "INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)"; session.execute(insertQuery); ```
Closing the Connection
It’s important to close the connection to the Cassandra cluster once you are done using it. Follow these steps to close the connection:
- Close the Session: Call the close() method on the session object to close the session.
- Close the Cluster: Call the close() method on the Cluster object to close the connection to the cluster.
By following these steps, you can successfully connect to Cassandra DB from Java and perform various database operations. Make sure to handle exceptions and errors appropriately to ensure the stability of your application.