Connecting to Cassandra DB in Java

03.03.2025

As a senior web developer, it’s important to have a good understanding of how to connect to different databases in various programming languages. In this article, we will focus on connecting to a Cassandra database using Java.

Java Database Connectivity(JDBC) Tutorial - Dinesh on Java

Setting up the Cassandra Java Driver

The first step in connecting to Cassandra in Java is to set up the Cassandra Java driver. You can include the driver as a dependency in your project using Maven or Gradle.

06 Connecting to Apache Cassandra – Build a messaging app …
Jan 2, 2022 … … Java Brains. #CodeWithMe #SpringBoot #Cassandra. … 03 Cassandra Data modeling – Build a messaging app (Spring Boot + Cassandra).

Maven Dependency:

  <dependency>     <groupId>com.datastax.cassandra</groupId>     <artifactId>cassandra-driver-core</artifactId>     <version>4.12.0</version> </dependency>  

Gradle Dependency:

  implementation 'com.datastax.cassandra:cassandra-driver-core:4.12.0'  

Connecting to Cassandra

Once you have included the Cassandra driver in your project, you can start connecting to a Cassandra cluster. Here is a simple example of how to connect to a Cassandra cluster:

  Cluster cluster = Cluster.builder()   .addContactPoint("127.0.0.1")   .withPort(9042)   .build();  Session session = cluster.connect();  

Executing Queries

After establishing a connection to the Cassandra cluster, you can execute queries to interact with the database. Here is an example of how to execute a simple query:

  ResultSet resultSet = session.execute("SELECT * FROM keyspace.table");  

You can also use prepared statements for executing queries with parameters:

  PreparedStatement preparedStatement = session.prepare("INSERT INTO keyspace.table (column1, column2) VALUES (?, ?)"); BoundStatement boundStatement = preparedStatement.bind(value1, value2); session.execute(boundStatement);  

Closing the Connection

It’s important to close the connection to the Cassandra cluster when you are done using it to free up resources. You can close the connection as follows:

  session.close(); cluster.close();  

Handling Exceptions

When working with databases, it’s important to handle exceptions properly. Make sure to catch and handle any exceptions that may occur during the connection or query execution process.

Conclusion

Connecting to a Cassandra database in Java is essential for building scalable and reliable web applications. By following the steps outlined in this article, you can easily establish a connection to a Cassandra cluster, execute queries, and handle exceptions effectively.

Do you like the article?

Yan Hadzhyisky

fullstack PHP+JS+REACT developer