Documentation Home
MySQL NDB Cluster API Developer Guide
Related Documentation Download this Manual
PDF (US Ltr) - 3.6Mb
PDF (A4) - 3.6Mb


MySQL NDB Cluster API Developer Guide  /  ...  /  NDB API Basic Connection Example

2.5.1.1 NDB API Basic Connection Example

This example, which can also be found in storage/ndb/ndbapi-examples/ndbapi_basic/ndbapi_basic_connect.cpp, demonstrates the use of Ndb_cluster_connection to connect to an NDB management server using a given connection string. On success, it obtains and prints out some information about the cluster. If it is unable to connect to the management or to the data nodes, it prints an appropriate error and exits.

#include <iostream>
#include <cstdlib>

#include <NdbApi.hpp>

namespace
{
  inline void test_connection(const Ndb_cluster_connection &connection)
  {
    std::cout << "Connected to: " << connection.get_system_name()
              << ",\n\ton port: " << connection.get_connected_port()
              << ",\n\tactive NDBDs: " << connection.get_active_ndb_objects()
              << std::endl;
  }
}

int main(int argc, char **argv)
{
  if (argc != 2)
  {
    std::cout << "Usage: ndb_ndbapi_basic_connect <connectstring>"
              << std::endl;
    return EXIT_FAILURE;
  }

  const char *connectstring = argv[1];

  ndb_init();
  {
    Ndb_cluster_connection connection(connectstring);
    if (connection.connect() != 0)
    {
      std::cout << "Cannot connect to cluster management server" << std::endl;
      return EXIT_FAILURE;
    }

    if (connection.wait_until_ready(30, 0) != 0)
    {
      std::cout << "Cluster was not ready within 30 secs" << std::endl;
      return EXIT_FAILURE;
    }

    // Let's verify connection
    test_connection(connection);
  }
  ndb_end(0);

  return EXIT_SUCCESS;
}