2.1.2.3 Establishing the Connection

To establish a connection to the server, you must create an instance of Ndb_cluster_connection, whose constructor takes as its argument a cluster connection string. If no connection string is given, localhost is assumed.

The cluster connection is not actually initiated until the Ndb_cluster_connection::connect() method is called. When invoked without any arguments, the connection attempt is retried indefinitely, once per second, until successful. No reporting is done until the connection has been made.

By default an API node connects to the nearest data node. This is usually a data node running on the same machine as the nearest, due to the fact that shared memory transport can be used instead of the slower TCP/IP. This may lead to poor load distribution in some cases, so it is possible to enforce a round-robin node connection scheme by calling the set_optimized_node_selection() method with 0 as its argument prior to calling connect().

The connect() method initiates a connection to a cluster management node only, without waiting for any connections to be made to data nodes. You ca override this behavior by using wait_until_ready() after calling connect(). The wait_until_ready() method waits up to a given number of seconds for a connection to a data node to be established.

In the following example, initialization and connection are handled in the two functions example_init() and example_end(), which are included in subsequent examples by means of including the file example_connection.h.

Example 2-1: Connection example. 

#include <stdio.h>
#include <stdlib.h>
#include <NdbApi.hpp>
#include <mysql.h>
#include <mgmapi.h>

Ndb_cluster_connection* connect_to_cluster();
void disconnect_from_cluster(Ndb_cluster_connection *c);

Ndb_cluster_connection* connect_to_cluster()
{
  Ndb_cluster_connection* c;

  if(ndb_init())
    exit(EXIT_FAILURE);

  c= new Ndb_cluster_connection();

  if(c->connect(4, 5, 1))
  {
    fprintf(stderr, "Unable to connect to cluster within 30 seconds.\n\n");
    exit(EXIT_FAILURE);
  }

  if(c->wait_until_ready(30, 0) < 0)
  {
    fprintf(stderr, "Cluster was not ready within 30 seconds.\n\n");
    exit(EXIT_FAILURE);
  }

  return c; 
}

void disconnect_from_cluster(Ndb_cluster_connection *c)
{
  delete c;

  ndb_end(2);
}

int main(int argc, char* argv[])
{
  Ndb_cluster_connection *ndb_connection= connect_to_cluster();

  printf("Connection Established.\n\n");

  disconnect_from_cluster(ndb_connection);

  return EXIT_SUCCESS;
}