Friday, June 30, 2006

Writing NDBAPI programs - connecting to MySQL Cluster

In this first little lesson we will learn how to connect an NDBAPI program to connect to MySQL Cluster. Start a X node cluster with atleast two or three [API] or [MYSQLD] slots so that you can connect a mysql server and the example program.

Before running these examples, please read the documentation on the NDBAPI classes and methods that are used!

The first example program (listed below), ndbapi_connect.cpp illustrates how to connect to MySQL Cluster.

> cat ndbapi_connect.cpp

#include
#include

#include


using namespace std;

int main()
{
ndb_init();
/**
* define a connect string to the management server
*/
char * connectstring = "localhost";

/**
* Create a Ndb_cluster_connection object using the connectstring
*/

Ndb_cluster_connection * conn = new Ndb_cluster_connection(connectstring);


/**
* Connect to the management server
* try 12 times, wait 5 seconds between each retry,
* and be verbose (1), if connection attempt failes
*/

if(conn->connect(12, 5, 1) != 0)
{
cout << "Unable to connect to management server." << face="courier new"> return -1;
}

/**
* Join the cluster
* wait for 30 seconds for first node to be alive, and 0 seconds
* for the rest.
*/

if (conn->wait_until_ready(30,0) <0)
{
cout << "Cluster nodes not ready in 30 seconds." << endl;
return -1;
}

cout << "Congratulations, you have connected to MySQL Cluster!" << endl;
cout << "run 'ndb_mgm -e \"show\" to see that your app is connected! " << endl << "Press any key to exit" << endl;

char data;
read (0, &data, 1);

return 0;
}


To build this I do:
g++ -c -I/home/johan/mysql/include/ -I/home/johan/mysql/include/ndb -I/home/johan/mysql/include/ndb/ndbapi ndbapi_connect.cpp

and to link:
g++ ndbapi_connect.o -L/home/johan/mysql/lib -lndbclient -lmysys -lmystrings -lpthread -o ndbapi_connect

and to run:
./ndbapi_connect

It should print out:

Congratulations, you have connected to MySQL Cluster!
run 'ndb_mgm -e "show" to see that your app is connected!
Press any key to exit

Congratulations, you have now written your first NDBAPI example.
Next time we will look how to implement a simple query, SELECT b,c FROM t1 WHERE a=1 , using the NDBAPI.

1 comment:

Dean Swift said...

Example cluster configurations can be obtained by accessing the MySQL Cluster Configuration Demo Tool.