Screen-2BShot-2B2015-06-06-2Bat-2B10.11.32-2BPM

Cassandra Connection with Maven in Eclipse IDE using Datastax Java Driver

Below tutorial will show you the example to connect to Cassandra using Datastax Java Driver. I have used 2.1.6 version of the driver for the example.

1) Create a Maven project in Eclipse IDE.
2) Click on Next button
3) Select Maven Archetype. For this one I have chosen maven-archetype-quickstart and click on Next button.
4) Provide GroupID and ArtifactID and click on Finish button.
5) Add Datastax Cassandr Driver dependency in pom.xml file. It will add the JAR file to the build path.
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.6</version>
</dependency>
7) Get the Cluster object instance
Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(9042).build();
8) Get the Session object instance
Session session = cluster.connect();
9) Provide the CQL query to execute
session.execute("use cassandrademo");
where cassandrademo is the keyspace name
10) To get the ResultSet object use
ResultSet resultSet = session.execute("select * from users");
Here is the full source code:
package com.cassandra.cassandrademo;
import java.util.List;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class CassandraConnector {
public static void main(String[] args) {
Cluster cluster = Cluster.builder().addContactPoint("localhost")
.withPort(9042).build();
Session session = cluster.connect();
System.out.println("session object---" + session);
session.execute("use cassandrademo");
ResultSet resultSet = session.execute("select * from users");
List<Row> results = resultSet.all();
for (Row row : results) {
System.out.println(row.getInt(0));
System.out.println(row.getString(2));
}
session.close();
}
}

Output:

session object---com.datastax.driver.core.SessionManager@20346642
1
FondOfIt

Leave a Reply

Your email address will not be published. Required fields are marked *