Illustration Image

Cassandra.Link

The best knowledge base on Apache Cassandra®

Helping platform leaders, architects, engineers, and operators build scalable real time data platforms.

10/23/2020

Reading time:5 min

DataStax-Examples/quickstart-c

by DataStax-Examples

A basic demo CRUD application using the DataStax C/C++ Driver for Apache Cassandra. Run the quickstart_complete.c file if you want to skip the exercise and run the application with the complete code.Contributors: Rebecca MillsObjectivesTo demonstrate how to perform basic CRUD operations with the DataStax C/C++ Driver.The intent is to help users get up and running quickly with the driver.How this Sample WorksThis project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.Project Layoutquickstart.c - main application file with space to fill in CRUD operation codeusers.cql - Use this file to create the schemaPrerequisitesA running instance of Apache Cassandra® 1.2+CMake v2.6.4+libuv 1.xOpenSSL v1.0.x or v1.1.xCreate the keyspace and tableThe users.cql file provides the schema used for this project:CREATE KEYSPACE demo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};CREATE TABLE demo.users ( lastname text PRIMARY KEY, age int, city text, email text, firstname text);Getting the DriverYou can obtain binary versions of the driver, available for various operating systems and architectures, from our DataStax download server.The driver source code is available via GitHub.The C/C++ driver will build on most standard Unix-like and Microsoft Windows platforms. Packages are available for the following platforms:CentOS 6CentOS 7Ubuntu 14.04 LTSUbuntu 16.04 LTSUbuntu 18.04 LTSWindowsIf you are on MacOS, once you have the source code and nescesaary dependencies, you can build the driver with CMake:mkdir buildpushd buildcmake ..makemake installpopdFor more help with getting dependencies and building the driver from source code on different operating systems, check out the documentation on building the driver.Once you have completed filling in the code blocks (with the driver installed on Linux/MacOS) you also have the option of generating the quickstart executable with CMake, and the CMake configuration file provided. Follow these steps:Clone quickstart-c repositorycd quickstart-cmkdir buildcd buildcmake ..makeConnect to your clusterAll of our code is contained in the quickstart.c file.A new CassCluster object will need to be created and configured to connect a session to our Cassandra instance. The minimal configuration needed to connect is a list of hosts. If you are not using localhost for your instance, provide the ip address of of your node in the main() function.// TO DO: Fill in your own host int main(int argc, char* argv[]) { CassCluster* cluster = NULL; CassSession* session = cass_session_new(); char* hosts = "127.0.0.1"; char* keyspace = "demo";CRUD OperationsFill the code in the functions that will add a user, get a user, update a user and delete a user from the table with the driver.INSERT a userCassError insert_user(CassSession* session, const Users* users) { CassError rc = CASS_OK; CassStatement* statement = NULL; CassFuture* future = NULL; // TO DO: execute a simple statement that inserts one user into the table const char* query = "INSERT INTO users (lastname, age, city, email, firstname) VALUES (?, ?, ?, ?, ?)"; statement = cass_statement_new(query, 5); cass_statement_bind_string(statement, 0, users->lastname); cass_statement_bind_int32(statement, 1, users->age); cass_statement_bind_string(statement, 2, users->city); cass_statement_bind_string(statement, 3, users->email); cass_statement_bind_string(statement, 4, users->firstname); future = cass_session_execute(session, statement); cass_future_wait(future); rc = cass_future_error_code(future); if (rc != CASS_OK) { print_error(future); } cass_future_free(future); cass_statement_free(statement); return rc;}SELECT a userCassError select_user(CassSession* session, const char* lastname) { CassError rc = CASS_OK; CassStatement* statement = NULL; CassFuture* future = NULL; // TO DO: execute a simple statement that retrieves one user from the table const char* query = "SELECT * FROM users WHERE lastname=?"; statement = cass_statement_new(query, 1); cass_statement_bind_string(statement, 0, lastname); future = cass_session_execute(session, statement); cass_future_wait(future); rc = cass_future_error_code(future); if (rc != CASS_OK) { print_error(future); } else { const CassResult* result = cass_future_get_result(future); const CassRow* row = cass_result_first_row(result); if (row) { const char *firstname = NULL; size_t firstname_length = 0; cass_int32_t age = 0; //TO DO: print firstname and age of user cass_value_get_string(cass_row_get_column_by_name(row, "firstname"), &firstname, &firstname_length); cass_value_get_int32(cass_row_get_column_by_name(row, "age"), &age); printf("firstname: '%.*s' age: %d\n", (int)firstname_length, firstname, age); } cass_result_free(result); } cass_statement_free(statement); cass_future_free(future); return rc;}UPDATE a user's ageCassError update_user_age(CassSession* session, const char* lastname, cass_int32_t age) { CassError rc = CASS_OK; CassStatement* statement = NULL; CassFuture* future = NULL; // TO DO: execute a simple statement that updates the age of one user const char* query = "UPDATE users SET age =? WHERE lastname =?"; statement = cass_statement_new(query, 2); cass_statement_bind_int32(statement, 0, age); cass_statement_bind_string(statement, 1, lastname); future = cass_session_execute(session, statement); cass_future_wait(future); rc = cass_future_error_code(future); if (rc != CASS_OK) { print_error(future); } cass_future_free(future); cass_statement_free(statement); return rc;}DELETE a userCassError delete_user(CassSession* session, const char* lastname) { CassError rc = CASS_OK; CassStatement* statement = NULL; CassFuture* future = NULL; const char* query = "DELETE FROM users WHERE lastname=?"; statement = cass_statement_new(query, 1); cass_statement_bind_string(statement, 0, lastname); future = cass_session_execute(session, statement); cass_future_wait(future); rc = cass_future_error_code(future); if (rc != CASS_OK) { print_error(future); } cass_future_free(future); cass_statement_free(statement); return rc;}LicenseCopyright 2019 Rebecca MillsLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

Illustration Image

Build Status

A basic demo CRUD application using the DataStax C/C++ Driver for Apache Cassandra. Run the quickstart_complete.c file if you want to skip the exercise and run the application with the complete code.

Contributors: Rebecca Mills

Objectives

  • To demonstrate how to perform basic CRUD operations with the DataStax C/C++ Driver.
  • The intent is to help users get up and running quickly with the driver.

How this Sample Works

This project walks through basic CRUD operations using Cassandra. The demo application will first insert a row of user data, select that same row back out, update the row and finally delete the user. The README includes the code snippets to be filled in to the main application code to complete the functionality.

Project Layout

  • quickstart.c - main application file with space to fill in CRUD operation code
  • users.cql - Use this file to create the schema

Prerequisites

Create the keyspace and table

The users.cql file provides the schema used for this project:

CREATE KEYSPACE demo
    WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
CREATE TABLE demo.users (
    lastname text PRIMARY KEY,
    age int,
    city text,
    email text,
    firstname text);

Getting the Driver

You can obtain binary versions of the driver, available for various operating systems and architectures, from our DataStax download server.The driver source code is available via GitHub.The C/C++ driver will build on most standard Unix-like and Microsoft Windows platforms. Packages are available for the following platforms:

If you are on MacOS, once you have the source code and nescesaary dependencies, you can build the driver with CMake:

mkdir build
pushd build
cmake ..
make
make install
popd

For more help with getting dependencies and building the driver from source code on different operating systems, check out the documentation on building the driver.

Once you have completed filling in the code blocks (with the driver installed on Linux/MacOS) you also have the option of generating the quickstart executable with CMake, and the CMake configuration file provided. Follow these steps:

  • Clone quickstart-c repository
  • cd quickstart-c
  • mkdir build
  • cd build
  • cmake ..
  • make

Connect to your cluster

All of our code is contained in the quickstart.c file. A new CassCluster object will need to be created and configured to connect a session to our Cassandra instance. The minimal configuration needed to connect is a list of hosts. If you are not using localhost for your instance, provide the ip address of of your node in the main() function.

// TO DO: Fill in your own host 
int main(int argc, char* argv[]) {
  CassCluster* cluster = NULL;
  CassSession* session = cass_session_new();
  char* hosts = "127.0.0.1";
  char* keyspace = "demo";

CRUD Operations

Fill the code in the functions that will add a user, get a user, update a user and delete a user from the table with the driver.

INSERT a user

CassError insert_user(CassSession* session, const Users* users) {
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture* future = NULL;
  
  // TO DO: execute a simple statement that inserts one user into the table
  const char* query =
      "INSERT INTO users (lastname, age, city, email, firstname) VALUES (?, ?, ?, ?, ?)";
  statement = cass_statement_new(query, 5);
  cass_statement_bind_string(statement, 0, users->lastname);
  cass_statement_bind_int32(statement, 1, users->age);
  cass_statement_bind_string(statement, 2, users->city);
  cass_statement_bind_string(statement, 3, users->email);
  cass_statement_bind_string(statement, 4, users->firstname);
  future = cass_session_execute(session, statement);
  cass_future_wait(future);
  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    print_error(future);
  }
  cass_future_free(future);
  cass_statement_free(statement);
  return rc;
}

SELECT a user

CassError select_user(CassSession* session, const char* lastname) {
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture* future = NULL;
  
  // TO DO: execute a simple statement that retrieves one user from the table
  const char* query = "SELECT * FROM users WHERE lastname=?";
  statement = cass_statement_new(query, 1);
  cass_statement_bind_string(statement, 0, lastname);
  future = cass_session_execute(session, statement);
  cass_future_wait(future);
  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    print_error(future);
  } else {
    const CassResult* result = cass_future_get_result(future);
    const CassRow* row = cass_result_first_row(result);
    if (row) {
      const char *firstname = NULL;
      size_t firstname_length = 0;
      cass_int32_t age = 0;
      //TO DO: print firstname and age of user
      cass_value_get_string(cass_row_get_column_by_name(row, "firstname"), &firstname,
                            &firstname_length);
      cass_value_get_int32(cass_row_get_column_by_name(row, "age"), &age);
      printf("firstname: '%.*s' age: %d\n", (int)firstname_length, firstname, age);
    }
    cass_result_free(result);
  }
  cass_statement_free(statement);
  cass_future_free(future);
  return rc;
}

UPDATE a user's age

CassError update_user_age(CassSession* session, const char* lastname, cass_int32_t age) {
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture* future = NULL;
  
  // TO DO: execute a simple statement that updates the age of one user
  const char* query = "UPDATE users SET age =? WHERE lastname =?";
  statement = cass_statement_new(query, 2);
  cass_statement_bind_int32(statement, 0, age);
  cass_statement_bind_string(statement, 1, lastname);
  future = cass_session_execute(session, statement);
  cass_future_wait(future);
  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    print_error(future);
  }
  cass_future_free(future);
  cass_statement_free(statement);
  return rc;
}

DELETE a user

CassError delete_user(CassSession* session, const char* lastname) {
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture* future = NULL;
  const char* query = "DELETE FROM users WHERE lastname=?";
  statement = cass_statement_new(query, 1);
  cass_statement_bind_string(statement, 0, lastname);
  future = cass_session_execute(session, statement);
  cass_future_wait(future);
  rc = cass_future_error_code(future);
  if (rc != CASS_OK) {
    print_error(future);
  }
  cass_future_free(future);
  cass_statement_free(statement);
  return rc;
}

License

Copyright 2019 Rebecca Mills

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Related Articles

examples
cassandra
datastax

GitHub - datastaxdevs/workshop-betterreads: Clone of Good Reads using Spring and Cassandra

datastaxdevs

12/2/2023

Checkout Planet Cassandra

Claim Your Free Planet Cassandra Contributor T-shirt!

Make your contribution and score a FREE Planet Cassandra Contributor T-Shirt! 
We value our incredible Cassandra community, and we want to express our gratitude by sending an exclusive Planet Cassandra Contributor T-Shirt you can wear with pride.

Join Our Newsletter!

Sign up below to receive email updates and see what's going on with our company

Explore Related Topics

AllKafkaSparkScyllaSStableKubernetesApiGithubGraphQl

Explore Further

cplusplus