Skip to content

Instantly share code, notes, and snippets.

@beccam
Last active July 21, 2017 21:02
Show Gist options
  • Save beccam/fd8080820a7f08bac9d4 to your computer and use it in GitHub Desktop.
Save beccam/fd8080820a7f08bac9d4 to your computer and use it in GitHub Desktop.
Getting Started with Apache Cassandra and Java Part II
import com.datastax.driver.core.*;
public class GettingStartedTwo {
public static void main(String[] args) {
Cluster cluster;
Session session;
ResultSet results;
Row rows;
// Connect to the cluster and keyspace "demo"
cluster = Cluster
.builder()
.addContactPoint("localhost")
.withRetryPolicy(DefaultRetryPolicy.INSTANCE)
.withLoadBalancingPolicy(
new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
.build();
session = cluster.connect("demo");
// Insert one record into the users table
PreparedStatement statement = session.prepare(
"INSERT INTO users" + "(lastname, age, city, email, firstname)"
+ "VALUES (?,?,?,?,?);");
BoundStatement boundStatement = new BoundStatement(statement);
session.execute(boundStatement.bind("Jones", 35, "Austin",
"[email protected]", "Bob"));
// Use select to get the user we just entered
Statement select = QueryBuilder.select().all().from("demo", "users")
.where(eq("lastname", "Jones"));
results = session.execute(select);
for (Row row : results) {
System.out.format("%s %d \n", row.getString("firstname"),
row.getInt("age"));
}
// Update the same user with a new age
Statement update = QueryBuilder.update("demo", "users")
.with(QueryBuilder.set("age", 36))
.where((QueryBuilder.eq("lastname", "Jones")));
session.execute(update);
// Select and show the change
select = QueryBuilder.select().all().from("demo", "users")
.where(eq("lastname", "Jones"));
results = session.execute(select);
for (Row row : results) {
System.out.format("%s %d \n", row.getString("firstname"),
row.getInt("age"));
}
// Delete the user from the users table
Statement delete = QueryBuilder.delete().from("users")
.where(QueryBuilder.eq("lastname", "Jones"));
results = session.execute(delete);
// Show that the user is gone
select = QueryBuilder.select().all().from("demo", "users");
results = session.execute(select);
for (Row row : results) {
System.out.format("%s %d %s %s %s\n", row.getString("lastname"),
row.getInt("age"), row.getString("city"),
row.getString("email"), row.getString("firstname"));
}
// Clean up the connection by closing it
cluster.close();
}
}
@tcpip4000
Copy link

line 18 error: should use the builder method:

new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()))

This is a workaround think should use the init method first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment