You have learned how to use cqlsh to access an ApsaraDB for Cassandra instance. However, in practice, you may need to write code to access an ApsaraDB for Cassandra instance, rather than merely connecting to a node and typing some CQL statements like you would do in cqlsh. You may need to connect to multiple Cassandra nodes, evenly distribute requests to each Cassandra node, and manage connection pools. You do not have to worry about this because the community versions of SDKs have already implemented these features. The following sections describe how to use the SDKs to access an ApsaraDB for Cassandra instance.

Preparations

1. Obtain the endpoint

Log on to the ApsaraDB for Cassandra console. Click a cluster ID to go to the Cluster Details page of the cluster. In the left-side navigation pane, click Database Connection.detail

For security considerations, Internet connection is disabled by default. To obtain the public endpoint, enable Internet connection as shown in the preceding figure. Endpoints in the following formats are obtained:

cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com
cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com 
			

The number of endpoints varies with the cluster size. Use as many endpoints as possible. This helps prevent failure to connect to the cluster due to the failure of a single node. The methods for accessing an ApsaraDB for Cassandra instance over the Internet and internal network are almost identical except that different endpoints are used. The following examples use Java and Python code.

2. Add IP addresses to a whitelist

Before you access an ApsaraDB for Cassandra instance, ensure that you have added the IP addresses of clients to the instance whitelist. For more information, visit Configure a whitelist.

Multi-language sample code

1. Java-based access

1.1 Add a Maven dependency

<dependency>
    <groupId>com.taobao.pandora</groupId>
    <artifactId>odps-sdk-core</artifactId>
    <version>3.7.1</version>
</dependency>
			

This reference introduces some public libraries. To avoid unnecessary trouble caused by dependency conflicts, test the dependency in a new project first.

1.2 Write Java code for the access

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PlainTextAuthProvider;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;

public class Demo {

  public static void main(String[] args) {

    // Enter the public or internal endpoints of the database. You can enter as many endpoints as provided by the console.
    // In fact, the SDK will only connect to the first accessible endpoint and establish a control connection. You can enter multiple endpoints to avoid database connection failure caused by the failure of a single node.
    // Ignore the sequence of the endpoints, because the SDK may rearrange the sequence to prevent different clients from connecting to the same endpoint.
    // You must enter only public endpoints or only internal endpoints.
    String[] contactPoints = new String[]{
      "cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com",
      "cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com"
    };

    Cluster cluster = Cluster.builder()
      .addContactPoints(contactPoints)
      // Enter the account name and password. If you forget the password, you can reset it on the Accounts page.
      .withAuthProvider(new PlainTextAuthProvider("cassandra", "123456"))
      // If you access the Cassandra cluster over the Internet, you must append @public to the account name to switch to full Internet link.
      // Otherwise, you cannot connect to all internal nodes over the Internet, and exceptions or delays will occur, affecting local development and debugging.
      // Automatic identification of network links will be supported in the future, eliminating the need to manually add @public. For more information, see changelogs on the official website.
      //.withAuthProvider(new PlainTextAuthProvider("cassandra@public", "123456"))
      .build();

    // Initialize the cluster. A control connection will be established at this time. This step can be ignored, because the init method is automatically called when a session is established.
    cluster.init();

    // Connect to the cluster. A persistent connection pool will be established for each Cassandra node.
    // Therefore, it is burdensome to create one session for each request. We recommend that you create several sessions in advance for each process.
    // As a general rule, one session is sufficient. You can make adjustments based on your actual needs. For example, you can manage the read and write sessions separately.
    Session session = cluster.connect();

    // Query the permission-related table to view the number of created roles.
    // This is the system table. By default, only the superuser account cassandra has the SELECT permission.
    // If you use another account for testing, you can switch to another table or grant the SELECT permission to the account.
    ResultSet res = session.execute("SELECT * FROM system_auth.roles");

    // ResultSet implements the Iterable interface to display each line of information in the console.
    res.forEach(System.out::println);

    // Close the session.
    sqlSession.close();

    // Shut down the cluster.
    writer.close();
  }

}

			

2. Python-based access

2.1 Install the SDK library

# Install the specified version. Python 3.x is recommended.
pip install cassandra-driver==3.19.0
# Install the latest version.
pip install cassandra-driver
# https://pypi.org/project/cassandra-driver/#history
			

2.2 Write Python code for the access

#! /usr/bin/env python
# -*- coding: UTF-8 -*-

import logging
import sys
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider

logging.basicConfig(stream=sys.stdout, level=logging.INFO)


cluster = Cluster(
    # Enter the public or internal endpoints of the database. You can enter as many endpoints as provided by the console.
    # In fact, the SDK will only connect to the first accessible endpoint and establish a control connection. You can enter multiple endpoints to avoid database connection failure caused by the failure of a single node.
    # Ignore the sequence of the endpoints, because the SDK may rearrange the sequence to prevent different clients from connecting to the same endpoint.
    # You must enter only public endpoints or only internal endpoints.
    contact_points=["cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com",
                    "cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com"],
    # Enter the account name and password. If you forget the password, you can reset it on the Accounts page.
    auth_provider=PlainTextAuthProvider("cassandra", "123456"))
    # If you access the Cassandra cluster over the Internet, you must append @public to the account name to switch to full Internet link.
    # Otherwise, you cannot connect to all internal nodes over the Internet, and exceptions or delays will occur, affecting local development and debugging.
    # Automatic identification of network links will be supported in the future, eliminating the need to manually add @public. For more information, see changelogs on the official website.
    # auth_provider=PlainTextAuthProvider("cassandra@public", "123456"))

# Connect to the cluster. A persistent connection pool will be established for each Cassandra node.
# Therefore, it is burdensome to create one session for each request. We recommend that you create several sessions in advance for each process.
# As a general rule, one session is sufficient. You can make adjustments based on your actual needs. For example, you can manage the read and write sessions separately.
session = cluster.connect()

# Query the permission-related table to view the number of created roles.
# This is the system table. By default, only the superuser account cassandra has the SELECT permission.
# If you use another account for testing, you can switch to another table or grant the SELECT permission to the account.
rows = session.execute('SELECT * FROM system_auth.roles')

# Display each line of information in the console.
for row in rows:
    print("# row: {}".format(row))

# Close the session.
session.shutdown()

# Shut down the cluster.
cluster.shutdown()
			

3. Access in other programming languages

The access interfaces for other programming languages are similar to those of Python and Java and can be found in the GitHub community documentation.