Today while I was coding a DNS plugin against a MariaDB database, I realized that after a long idle time database closes the connection. After googling for a moment, I realized that both MySQL and MariaDB offer in their API a mechanism to allow reconnections.  So here it is the way I did it.

MYSQL *conn, *mystatus;
my_bool reconnect = 1;
conn = mysql_init(NULL);
mysql_options(conn, MYSQL_OPT_RECONNECT, &reconnect);
mystatus = mysql_real_connect(conn, MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB, 0, NULL, 0);

The key here is to add the mysql_options call before the mysql_real_connect.

Modify this to fit your needs.

";