Created
December 30, 2015 00:05
-
-
Save MBtech/83436974fa7a9089ae69 to your computer and use it in GitHub Desktop.
Cassandra Java Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package mb.learningcurve.Cassandra; | |
import com.datastax.driver.core.Cluster; | |
import com.datastax.driver.core.ResultSet; | |
import com.datastax.driver.core.Row; | |
import com.datastax.driver.core.Session; | |
/** | |
* | |
* @author mb | |
*/ | |
public class CassandraExample { | |
private Cluster cluster; | |
private Session session; | |
public static void main(String[] args) { | |
CassandraExample c = new CassandraExample(); | |
c.createSchema(); | |
c.mainFunction(); | |
} | |
public void mainFunction(){ | |
session.execute("INSERT INTO users (lastname, age, city, email, firstname) VALUES ('Jones', 35, 'Austin', '[email protected]', 'Bob')"); | |
// Use select to get the user we just entered | |
ResultSet results = session.execute("SELECT * FROM users WHERE lastname='Jones'"); | |
for (Row row : results) { | |
System.out.format("%s %d\n", row.getString("firstname"), row.getInt("age")); | |
} | |
// Update the same user with a new age | |
session.execute("update users set age = 36 where lastname = 'Jones'"); | |
// Select and show the change | |
results = session.execute("select * from users where lastname='Jones'"); | |
for (Row row : results) { | |
System.out.format("%s %d\n", row.getString("firstname"), row.getInt("age")); | |
} | |
// Delete the user from the users table | |
session.execute("DELETE FROM users WHERE lastname = 'Jones'"); | |
// Show that the user is gone | |
results = session.execute("SELECT * FROM users"); | |
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(); | |
} | |
public void createSchema() { | |
cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); | |
session = cluster.connect(); | |
session.execute("CREATE KEYSPACE IF NOT EXISTS demo WITH replication " | |
+ "= {'class':'SimpleStrategy', 'replication_factor':1};"); | |
session.execute("CREATE TABLE demo.users (" + "lastname text PRIMARY KEY," | |
+ "age int," + "city text," + "email text," | |
+ "firstname text" + ");"); | |
session = cluster.connect("demo"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment