MySQL C API: you need an example to start the database in * Built-in * mode

I am working on a C tool in which I need to intensively manipulate and retrieve internal process data.

Therefore, I decided to use the MySQL C API in Embedded mode, so I can have a built-in database for each running process of my tool and use all the SQL functions on it.

All the MySQL C API tutorials I found on the Internet relate to connecting to a running server, which is not my case.

There are several examples of working with Embedded on the Oracle MySQL website, but they are not simple and hard to get them to work.

Q: Can someone point me or write me a short example for starting a database using the MySQL C API in Embedded mode?

Thanks!

0
c mysql embedded-database
source share
1 answer

After many attempts, finally answering a question about yourself and sharing it with you:

  • Create a central data directory that will be used to store the database. In this example, I will use /tmp/mysql_embedded_data

> mkdir /tmp/mysql_embedded_data

  • Create a C file, as in the following example:
 #include <my_global.h> #include <mysql.h> int main(int argc, char **argv) { static char *server_options[] = { "mysql_test", // An unused string "--datadir=/tmp/mysql_embedded_data", // Your data dir NULL }; int num_elements = (sizeof(server_options) / sizeof(char *)) - 1; static char *server_groups[] = { "libmysqld_server", "libmysqld_client", NULL }; // Init MySQL lib and connection mysql_library_init(num_elements, server_options, server_groups); MYSQL *con = mysql_init(NULL); if (con == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } mysql_options(con, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client"); mysql_options(con, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL); // Connect to no host/port -> Embedded mode if (mysql_real_connect(con, NULL, NULL, NULL, NULL, 0, NULL, 0) == NULL) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } // Create a sample empty DB, named "aNewDatabase" if (mysql_query(con, "CREATE DATABASE aNewDatabase")) { fprintf(stderr, "%s\n", mysql_error(con)); mysql_close(con); exit(1); } // Close connection mysql_close(con); exit(0); } 
  • Compile the file (I assume in this example that my file name is C /tmp/mysql_try.c )

gcc /tmp/mysql_try.c -o /tmp/mysql_try -lz `mysql_config --include --libmysqld-libs`

  • Run your compiled program:

> /tmp/mysql_try

  • When your program returns, make sure the database is created successfully. We named our example DB aNewDatabase , so we will check if it has a directory in the data directory that we created → We will check if the /tmp/mysql_embedded_data/aNewDatabase directory was created:

> ls /tmp/mysql_embedded_data/aNewDatabase db.opt

  • Enjoy it!
+2
source share

All Articles