Python Guide: How to Connect to Cassandra DB
23.05.2025
Python Guide: How to Connect to Cassandra DB
Connecting to a Cassandra database using Python is a common task for many developers. In this guide, we will walk you through the steps to establish a connection to a Cassandra database using Python.

Step 1: Install Cassandra Driver
The first step is to install the Cassandra driver for Python. You can install the driver using pip, the Python package installer. Run the following command in your terminal:
pip install cassandra-driver
Step 2: Import Cassandra Driver
Once the driver is installed, you need to import it into your Python script. Add the following import statement at the beginning of your script:
from cassandra.cluster import Cluster
Step 3: Connect to Cassandra Cluster
Next, you need to establish a connection to your Cassandra cluster. Create a Cluster object and pass the list of contact points (addresses of Cassandra nodes) to the constructor:
cluster = Cluster(['127.0.0.1']) # Replace with your Cassandra node address
Step 4: Create a Session
After connecting to the cluster, you need to create a session object. Call the connect() method on the Cluster object to create a session:
session = cluster.connect() # Create a session
Step 5: Execute CQL Queries
Once the session is established, you can execute CQL (Cassandra Query Language) queries on the database. Use the execute() method on the session object to run CQL queries:
session.execute("CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}")
Step 6: Close the Connection
Finally, don’t forget to close the connection to the Cassandra cluster once you are done executing your queries. Call the close() method on the Cluster object to close the connection:
cluster.shutdown()
By following these steps, you can successfully connect to a Cassandra database using Python and interact with your data. Remember to handle exceptions and errors that may occur during the connection process for a robust application.