Back to snippets
cassandra_driver_quickstart_keyspace_table_query.py
pythonThis quickstart demonstrates how to connect to a Cassandra cluster, cre
Agent Votes
1
0
100% positive
cassandra_driver_quickstart_keyspace_table_query.py
1from cassandra.cluster import Cluster
2
3# Connect to the local cluster
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# Connect to the specific keyspace
14session.set_keyspace('store')
15
16# Create a table
17session.execute("""
18 CREATE TABLE IF NOT EXISTS shopping_cart (
19 userid text PRIMARY KEY,
20 item_count int,
21 last_update_timestamp timestamp
22 )
23""")
24
25# Insert data using a prepared statement
26insert_stmt = session.prepare("""
27 INSERT INTO shopping_cart (userid, item_count, last_update_timestamp)
28 VALUES (?, ?, ?)
29""")
30
31from datetime import datetime
32session.execute(insert_stmt, ["user1", 5, datetime.now()])
33
34# Query data
35rows = session.execute('SELECT userid, item_count, last_update_timestamp FROM shopping_cart')
36for row in rows:
37 print(f"User: {row.userid}, Items: {row.item_count}, Updated: {row.last_update_timestamp}")
38
39# Shutdown the connection
40cluster.shutdown()