To connect to Cassandra in Java, you will need to include the Cassandra driver in your project. Here is an example of how you can do this:
-
- Download the Cassandra Java driver from the Apache Cassandra website or from Maven Central.
- Add the driver to your project. If you are using Maven, you can include the following dependency in your
pom.xml
file:
123com.datastax.cassandracassandra-driver-core3.9.0 - Import the driver classes in your Java code
12import com.datastax.driver.core.Cluster;import com.datastax.driver.core.Session; - Create a
Cluster
object and use it to create aSession
object.
12Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();Session session = cluster.connect(); - You can now use the
session
object to execute Cassandra queries
1session.execute("SELECT * FROM my_table WHERE id = 1"); - When you are finished with the session, you should close it to free up resources:
12session.close();cluster.close(); -
Full Example
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 |
import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; public class CassandraExample { public static void main(String[] args) { // Create a cluster object and use it to create a session Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect(); // Execute a query ResultSet resultSet = session.execute("SELECT * FROM my_table WHERE id = 1"); // Print the results for (Row row : resultSet) { System.out.println("id: " + row.getInt("id")); System.out.println("name: " + row.getString("name")); } // Close the session and cluster session.close(); cluster.close(); } } |
Insert Data into Cassandra
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class CassandraInsertExample { public static void main(String[] args) { // Create a cluster object and use it to create a session Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect(); // Insert some data session.execute("INSERT INTO pg_table (id, name) VALUES (1, 'Stephan')"); session.execute("INSERT INTO pg_table (id, name) VALUES (2, 'Bill')"); // Close the session and cluster session.close(); cluster.close(); } } |
The above program inserts two rows into a table named pg_table, with values for the id and name columns. You can specify different values for the id and name columns in each INSERT query to insert multiple rows.