Examples of Interacting with Cassandra or ScyllaDB using Python

To interact with Cassandra or ScyllaDB using Python, you can use the cassandra-driver library, which works for both databases.

pip install cassandra-driver

The following example demonstrates how to connect to a Cassandra or ScyllaDB cluster, create a keyspace, create a table, and perform basic CRUD (Create, Read, Update, Delete) operations.

from cassandra.cluster import Cluster

# Connect to the Cassandra or ScyllaDB cluster
cluster = Cluster(['127.0.0.1'])  # Replace with your actual cluster address
session = cluster.connect()

# Create a keyspace
keyspace_query = "CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"
session.execute(keyspace_query)

# Switch to the keyspace
session.set_keyspace('my_keyspace')

# Create a table
table_query = "CREATE TABLE IF NOT EXISTS my_table (id UUID PRIMARY KEY, name TEXT, age INT)"
session.execute(table_query)

# Insert data
insert_query = "INSERT INTO my_table (id, name, age) VALUES (uuid(), 'John Doe', 30)"
session.execute(insert_query)

# Query data
select_query = "SELECT * FROM my_table"
result = session.execute(select_query)

for row in result:
    print(f"ID: {row.id}, Name: {row.name}, Age: {row.age}")

# Update data
update_query = "UPDATE my_table SET age = 31 WHERE name = 'John Doe'"
session.execute(update_query)

# Query data after update
result = session.execute(select_query)

for row in result:
    print(f"ID: {row.id}, Name: {row.name}, Age: {row.age}")

# Delete data
delete_query = "DELETE FROM my_table WHERE name = 'John Doe'"
session.execute(delete_query)

# Query data after delete
result = session.execute(select_query)

for row in result:
    print(f"ID: {row.id}, Name: {row.name}, Age: {row.age}")

# Close the session and cluster connection
session.shutdown()
cluster.shutdown()