Hackerss.com

hackerss
hackerss

Posted on

Java Create a connection to a cassandra database


import java.sql.*;
import java.util.Properties;

public class CassandraConnection {

    public static void main(String[] args) {
        try {
            // Load the driver
            Class.forName("com.datastax.driver.core.Cluster");

            // Create a Properties object to store the parameters
            Properties props = new Properties();

            // Set the properties
            props.setProperty("user", "cassandra");
            props.setProperty("password", "cassandra");

            // Create a connection to the cluster and keyspace "demo"
            Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").withCredentials("cassandra", "cassandra").build();
            Session session = cluster.connect("demo");

            // Execute a query
            ResultSet rs = session.execute("SELECT * FROM test");

            // Iterate through the results and print them out
            for (Row row : rs) {
                System.out.println(row.getString("key") + ": " + row.getString("value"));
            }

            // Close the connection
            cluster.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)