Using MariaDB in C

Mike picture Mike · Jun 23, 2013 · Viewed 15.7k times · Source

I'm trying to connect to a MariaDB database in a C script and I can't find the necessary documentation. I installed libmariadbclient-dev, but I couldn't find any accompanying documentation such as a man page. There's a basic description and limited documentation here, but the documentation only includes descriptions of functions. The fact is, despite having scoured all sorts of Google results, I don't even know what to import to get this to work, much less how to use it. Is there any guide or documentation on how to use a MariaDB database in C?

Answer

David Ranieri picture David Ranieri · Jun 24, 2013

The MariaDB Client Library for C has exactly the same API as the MySQL Connector/C for MySQL 5.5

Here it is: http://dev.mysql.com/doc/refman/5.5/en/c-api-function-overview.html

Another one: http://zetcode.com/db/mysqlc/

You can compile a minimal test like

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{  
  MYSQL *con = mysql_init(NULL);

  if (con == NULL) 
  {
      fprintf(stderr, "%s\n", mysql_error(con));
      exit(1);
  }

  if (mysql_real_connect(con, "localhost", "root", "root_pswd", 
          NULL, 0, NULL, 0) == NULL) 
  {
      fprintf(stderr, "%s\n", mysql_error(con));
      mysql_close(con);
      exit(1);
  }  

  if (mysql_query(con, "CREATE DATABASE testdb")) 
  {
      fprintf(stderr, "%s\n", mysql_error(con));
      mysql_close(con);
      exit(1);
  }

  mysql_close(con);
  exit(0);
}

using

gcc -o mysql-test mysql-test.c $(mysql_config --libs)