How to use Cassandra CQL in your Java Application



Cassandra Query Language (CQL) is a SQL (Structured Query Language)-like language for querying Cassandra. Cassandra's data model is a partitioned row store with tunable consistency. Rows are organized into tables; the first component of a table's primary key is the partition key; within a partition, rows are clustered by the remaining columns of the key. Other columns can be indexed separately from the primary key.
Tables can be created, dropped, and altered at runtime without blocking updates and queries.

Cassandra does not support joins or subqueries, except for batch analysis through Hadoop. Rather, Cassandra emphasizes denormalization through features like collections.

CQL 3 is the default and primary interface into the Cassandra DBMS. CQL 3 provides a new API to Cassandra that is simpler than the Thrift API for new applications. The Thrift API, the Cassandra Command Line Interface (CLI), and legacy versions of CQL expose the internal storage structure of Cassandra. CQL 3 adds an abstraction layer that hides implementation details and provides native syntaxes for CQL 3 collections and other common encodings.


How to use CQL in your application


There are high-level clients that you can use in your application to send CQL queries to the cluster.For a basic application that does not require the features of the clients, you can use a CQL driver. The drivers manage connections, send queries and parse the response. Drivers are available for the following languages:

Import the Jar into your Project and try the Code Below. It should work fine.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlConnection {

 
 public static void main(String[] args) throws Exception{
 
  Connection con = null;
  try {
   Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
   con = 
DriverManager.getConnection("jdbc:cassandra://localhost:9160/Keyspace");

   String query = "SELECT * FROM column_family where gender=f ";

   Statement stmt = con.createStatement();
   ResultSet result = stmt.executeQuery(query);

   while (result.next()) {
    System.out.println(result.getString("user_name"));
    System.out.println(result.getString("gender"));
    System.out.println(result.getString("password"));
   }

  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
    con = null;
   }
  }

 }

Find Comments below or Add one

Post a Comment