Show List

Connect to Cassandra cluster using Java Driver



  1. To connect to a Cassandra cluster using the Java Driver, you need to follow these steps:

    1. Add Java Driver Dependency:

    Make sure you have added the Apache Cassandra Java Driver dependency to your project. You can do this using Maven, Gradle, or by manually including the JAR files in your project.

    For Maven, add the following dependency to your pom.xml:


    <dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>4.13.0</version> <!-- Use the latest version --> </dependency>

    2. Connect to the Cluster:


    import com.datastax.oss.driver.api.core.CqlSession; public class CassandraConnector { public static void main(String[] args) { // Set the contact points (IP addresses) of Cassandra nodes String[] contactPoints = {"127.0.0.1", "127.0.0.2"}; // Replace with your actual IPs // Create a CqlSession instance to connect to the cluster try (CqlSession session = CqlSession.builder().addContactPoints(contactPoints).build()) { System.out.printf("Connected to cluster: %s%n", session.getMetadata().getClusterName()); // Perform Cassandra operations here... } catch (Exception e) { System.out.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } } }

    3. Perform Cassandra Operations:

    Once connected, you can perform various Cassandra operations using the CqlSession instance. For example:


    // Execute a CQL query ResultSet resultSet = session.execute("SELECT * FROM keyspace_name.table_name"); // Iterate over the result set for (Row row : resultSet) { // Process each row } // Prepare and execute a parameterized query PreparedStatement preparedStatement = session.prepare("INSERT INTO keyspace_name.table_name (column1, column2) VALUES (?, ?)"); BoundStatement boundStatement = preparedStatement.bind(value1, value2); session.execute(boundStatement);

    4. Close the Session:

    Make sure to close the CqlSession instance when you're done using it to release resources:


    session.close();

    Note:

    • Replace "127.0.0.1", "127.0.0.2" with the actual IP addresses or hostnames of your Cassandra nodes.
    • Make sure your application has network access to the Cassandra cluster.
    • Handle exceptions appropriately, especially during session creation and query execution.
    • Ensure that your application's dependencies are compatible with the version of Cassandra you are connecting to.

    By following these steps, you can successfully connect to a Cassandra cluster using the Java Driver and perform database operations in your Java application.


    Leave a Comment


  • captcha text