Connecting to the server

#include <mysql/mysql.h>

MYSQL connection;

void connect(char *server, char *dbuser, char *passw)
{
  if (!mysql_connect(&connection,server,dbuser,passw))
  {
      fprintf(stderr, "Failed to connect to database:\
              Error: %s\n",mysql_error(&connection));
      exit(2);
  }
  mysql_select_db(&connection,"m23");
};
  1. First of all we have to include the necessary header file: #include <mysql/mysql.h>
  2. The mysql_connect function requires a MYSQL variable (here called connection) to store the connection data, a server name or ip, a valid mysql user and proper password. If all works correctly, mysql_connect will return 0, otherwise we get an error, print an error message and quit.

  3. mysql_error will generate a human readable error message.

  4. At least we should choose our database, this is done with mysql_select_db. Now the connection should be established.



root 2015-09-06