Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Java driver direct cql3

opuneet edited this page · 4 revisions
Clone this wiki locally

Astyanax allows users to use CQL3 directly. Here's an example. Consider the following simple schema.

Basic Setup
ColumnFamily<Integer, String> CF_EMPLOYEES = 
    new ColumnFamily<Integer, String>("EmployeeInfo", 
                              IntegerSerializer.get(), 
                      StringSerializer.get());
Create table query
keyspace.prepareQuery(CF_EMPLOYEES)
        .withCql("CREATE TABLE EmployeeInfo (id int PRIMARY KEY, fname text, lname text, age int, salary bigint)")
    .execute();
Simple query for Insert rows - entire row
keyspace.prepareQuery(CF_EMPLOYEES)
        .withCql("INSERT INTO astyanaxunittests.EmployeeInfo (id, fname, lname, age, salary) VALUES (1, 'Joe', 'Smith', 35, 100000)")
        .execute();
Simple query for Insert rows - specific columns only
keyspace.prepareQuery(CF_EMPLOYEES)
        .withCql("INSERT INTO astyanaxunittests.EmployeeInfo (id, fname, age) VALUES (1, 'Joe', 35)")
        .execute();
Using prepared statements for the inserts mentioned above
CqlQuery<Integer, String> query = 
        keyspace.prepareQuery(CF_EMPLOYEES)
        .withCql("INSERT INTO astyanaxunittests.EmployeeInfo (id, fname, lname, age, salary) VALUES (?,?,?,?,?)");

PreparedCqlQuery<Integer, String> pStatement = query.asPreparedStatement();

pStatement.withIntegerValue(1)
      .withStringValue("Joe")
      .withStringValue("Smith")
      .withIntegerValue(35)
      .withLongValue(100000L)
      .execute();

pStatement = query.asPreparedStatement();

pStatement.withIntegerValue(1)
      .withStringValue("Joe")
      .withIntegerValue(35)
      .execute();
Reading results from table
Rows<Integer, String> rows = 
        keyspace.prepareQuery(CF_EMPLOYEES)
        .withCql("SELECT * from astyanaxunittests.EmployeeInfo where id = 1")
        .execute()
        .getResult()
        .getRows();

for (Row<Integer, String> row : rows) {

    System.out.println("Row key: " + row.getKey());

    ColumnList<String> columns = row.getColumns();

    System.out.println("UserId:    " + columns.getColumnByName("id").getIntegerValue());
    System.out.println("FirstName: " + columns.getColumnByName("fname").getStringValue());
    System.out.println("LastName:  " + columns.getColumnByName("lname").getStringValue());
    System.out.println("Age:       " + columns.getColumnByName("age").getIntegerValue());
    System.out.println("Salary:    " + columns.getColumnByName("salary").getLongValue());
}
Using prepared statements for the above read query
pStatement = 
    keyspace.prepareQuery(CF_EMPLOYEES)
    .withCql("SELECT * from astyanaxunittests.EmployeeInfo where id = ?")
    .asPreparedStatement();

rows = pStatement.withIntegerValue(1)
        .execute()
        .getResult()
        .getRows();
Something went wrong with that request. Please try again.