This topic describes how to use a Cassandra client driver to connect to an ApsaraDB for Lindorm (Lindorm) cluster. Cassandra client drivers can be implemented by multiple languages, such as Python and C++. For more information about client drivers, see Client drivers.

Use a Cassandra client driver for Python to connect to a Lindorm cluster

Install a DataStax Python driver.

# Install a DataStax Python driver of a specified version. We recommend that you install DataStax Python driver 3.x.
pip install cassandra-driver==3.19.0
# Install a DataStax Python driver of the latest version.
pip install cassandra-driver
# https://pypi.org/project/cassandra-driver/#history

Write Python code to connect to a Lindorm cluster.

#!/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 endpoint or private endpoint of the Lindorm cluster that you want to connect. This parameter value cannot include a port number. 
    contact_points=["ip"],
    # Enter the username and the password that you use to connect to the Lindorm cluster. If you forget the password, you can reset the password on the Accounts page.
    auth_provider=PlainTextAuthProvider("cassandra", "123456"))

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

# Create a table.
session.execute(
                "CREATE TABLE IF NOT EXISTS testKeyspace.testTable (id int PRIMARY KEY, name text,age int,address text);");

# Insert data into a table.
session.execute(
                "INSERT INTO testKeyspace.testTable (id, name, age, address) VALUES ( 1, 'testname', 11, 'hangzhou');");

# Query data from a table.
rows = session.execute(
                "SELECT * FROM testKeyspace.testTable ;");

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

# Close a session.
session.shutdown()

# Disable a cluster.
cluster.shutdown()

Use a Cassandra client driver for C++ to connect to a Lindorm cluster

Obtain a Red Hat Package Manager (RPM) package. For more information, see DataStax C++ driver.

Write code to connect to a Lindorm cluster.

CassFuture* connect_future = NULL;
CassCluster* cluster = cass_cluster_new();
CassSession* session = cass_session_new();
char * hosts = "ip";//Enter the endpoint of the Lindorm cluster that you want to connect. You can query the value in the Lindorm console.

// Establish a connection.
cass_cluster_set_contact_points(cluster, hosts);
connect_future = cass_session_connect(session, cluster);

// Execute data definition language (DDL) statements.
if (cass_future_error_code(connect_future) == CASS_OK) {
    CassFuture* close_future = NULL;

    
    const char* query = "SELECT  name FROM testKeyspace.testTable ";
    CassStatement* statement = cass_statement_new(query, 0);

    CassFuture* result_future = cass_session_execute(session, statement);

    if (cass_future_error_code(result_future) == CASS_OK) {
      // Query the results.
      const CassResult* result = cass_future_get_result(result_future);
      const CassRow* row = cass_result_first_row(result);

      if (row) {
        const CassValue* value = cass_row_get_column_by_name(row, "name");
        // Display the results.
        const char* name;
        size_t name_length;
        cass_value_get_string(value, &name, &name_length);
        printf("release_version: '%.*s'\n", (int)name_length, name);
      }

      cass_result_free(result);
    } else {
      // Handle the exceptions.
      const char* message;
      size_t message_length;
      cass_future_error_message(result_future, &message, &message_length);
      fprintf(stderr, "Unable to run query: '%.*s'\n", (int)message_length, message);
    }

    cass_statement_free(statement);
    cass_future_free(result_future);

    // Release resources.
    close_future = cass_session_close(session);
    cass_future_wait(close_future);
    cass_future_free(close_future);
  } else {
    // Handle the exceptions.
    const char* message;
    size_t message_length;
    cass_future_error_message(connect_future, &message, &message_length);
    fprintf(stderr, "Unable to connect: '%.*s'\n", (int)message_length, message);
  }

  cass_future_free(connect_future);
  cass_cluster_free(cluster);
  cass_session_free(session);
            

Use a Cassandra client driver for Node.js to connect to a Lindorm cluster

Install a Cassandra client driver for Node.js.

npm install cassandra-driver 

Write code to connect to a Lindorm cluster.

const cassandra = require('cassandra-driver');

/**
* Enter the endpoint of the Lindorm cluster that you want to connect. Enter the username and the password. You can obtain the information in the Lindorm console. Set localDataCenter to datacenter1.
*/
const client = new cassandra.Client({ contactPoints: ['The endpoint of the Lindorm cluster. This parameter value cannot include a port number.'], localDataCenter: 'Database name', credentials: { username: 'Username', password: 'Password'} });

client.connect()
.then(() => client.execute("CREATE KEYSPACE IF NOT EXISTS lindormtest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '2' }"))
.then(() => client.execute("CREATE TABLE IF NOT EXISTS lindormtest.nodejs (name text PRIMARY KEY, age int)"))
.then(() => {
 return client.execute("INSERT INTO lindormtest.nodejs (name, age) VALUES ('lindorm', 10)");
})
.then(() => {
 return client.execute("SELECT name, age FROM lindormtest.nodejs WHERE name = 'lindorm' ");
})
.then(result => {
 const row = result.first();
 console.log('Obtained row: ', row);
 const p = row.age;
})
.finally(() => client.shutdown());
            

Use a Cassandra client driver for Go to connect to a Lindorm cluster

You can run the following command to install a Cassandra client driver for Go to connect to a Lindorm cluster. If you want to obtain dependency information about client drivers for Go, GoCQL, and Cassandra, go to the GoCQL official website or contact online support.

go get github.com/gocql/gocql

Write code to connect to a Lindorm cluster.

package main

import (
    "fmt"
    "log"

    "github.com/gocql/gocql"
)

func main() {
    // connect to the cluster
    cluster := gocql.NewCluster ("The endpoint of the Lindorm cluster. This parameter value cannot include a port number.")
    cluster.Authenticator = gocql.PasswordAuthenticator{
        Username:"Username",
        Password: "Password",
    }

    session, _ := cluster.CreateSession()
    defer session.Close()

    //create keyspace
    if err := session.Query(`CREATE KEYSPACE ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}`).Exec(); err != nil {
        log.Fatal(err)
    }

    // create table
    if err := session.Query(`CREATE TABLE ks.tb (cn1 text PRIMARY KEY, cn2 text, cn3 text)`).Exec(); err != nil {
        log.Fatal(err)
    }

    // insert  value
    if err := session.Query(`INSERT INTO ks.tb (cn1, cn2, cn3) VALUES (?, ?, ?)`,
        "v11", "v12", "v13").Exec(); err != nil {
        log.Fatal(err)
    }

    var column1 string
    var column2 string

    if err := session.Query(`SELECT cn1, cn2 FROM ks.tb WHERE cn1 = ?`,
        "v11").Consistency(gocql.One).Scan(&column1, &column2); err != nil {
        log.Fatal(err)
    }
    fmt.Println("ALL values:", column1, column2)

    var column3 string
    // list all tweets
    iter := session.Query(`SELECT * FROM ks.tb WHERE cn1 = ? `, "v11").Iter()
    for iter.Scan(&column1, &column2, &column3) {
        fmt.Println("ALL value:", column1, column2, column3)
    }
    if err := iter.Close(); err != nil {
        log.Fatal(err)
    }
}