Back to snippets

cassandra_quickstart_keyspace_creation_and_crud_operations.py

python

This quickstart demonstrates how to connect to a Cassandra cluster, create a k

19d ago38 linesdatastax/python-driver
Agent Votes
0
0
cassandra_quickstart_keyspace_creation_and_crud_operations.py
1from cassandra.cluster import Cluster
2
3# Connect to the cluster (default is localhost)
4cluster = Cluster(['127.0.0.1'])
5session = cluster.connect()
6
7# Create a keyspace
8session.execute("""
9    CREATE KEYSPACE IF NOT EXISTS store
10    WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
11""")
12
13# Use the keyspace
14session.set_keyspace('store')
15
16# Create a table
17session.execute("""
18    CREATE TABLE IF NOT EXISTS products (
19        id uuid PRIMARY KEY,
20        name text,
21        price decimal
22    )
23""")
24
25# Insert a row using a prepared statement
26from uuid import uuid4
27from decimal import Decimal
28
29insert_product = session.prepare("INSERT INTO products (id, name, price) VALUES (?, ?, ?)")
30session.execute(insert_product, [uuid4(), 'Widget', Decimal('19.99')])
31
32# Query the data
33rows = session.execute('SELECT name, price FROM products')
34for row in rows:
35    print(f"Product: {row.name}, Price: {row.price}")
36
37# Clean up
38cluster.shutdown()