To establish a connection to the server, it is necessary to
create an instance of Ndb_cluster_connection
,
whose constructor takes as its argument a cluster connectstring;
if no connectstring 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 each 1 second indefinitely until successful,
and no reporting is done. See
Section 2.3.24, “The Ndb_cluster_connection
Class”, for details.
By default an API node will connect to the
“nearest” data node — usually a data node
running on the same machine, 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()
. (See
Section 2.3.24.1.6, “Ndb_cluster_connection::set_optimized_node_selection()
”.)
The connect()
method initiates a connection
to a cluster management node only — it does not wait for
any connections to data nodes to be made. This can be
accomplished 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, initialisation and connection are
handled in the two functions example_init()
and example_end()
, which will be included in
subsequent examples via 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); } } 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; }