Have some C code that works on MySQL version 8.0 compiled with libmysqlclient-dev and for which I want to refactor the error messages on line 17 and 18:
// Compilation: gcc commerce.c -g -lm `mysql_config --cflags --libs` -Wall -o commerce
// Usage: ./commerce
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
#define FAIL_IF(EXP, MSG) ({ if (EXP) { printf(MSG "\n"); exit(EXIT_FAILURE); }})
int main (int argc, char *argv[]) {
MYSQL *conn = mysql_init(NULL);
FAIL_IF (conn == NULL, "mysql_init() failed\n");
FAIL_IF (mysql_real_connect(conn, "localhost", "root", "obfuscated", "commerce", 0, NULL, 0) == NULL, "Connection cannot be established because of incorrect credentials");
mysql_query(conn, "elect * from customers;");
MYSQL_RES *result = mysql_store_result(conn);
if (result == NULL) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); }
FAIL_IF (result == NULL, "An error was encountered.");
MYSQL_FIELD *field;
// print column names
printf("A total of %ld rows were returned with the following columns: ", mysql_num_rows(result));
while ((field = mysql_fetch_field(result))) {
printf("%s, ", field->name);
}
printf("\n");
mysql_free_result(result);
mysql_close(conn);
}
Note the deliberate typo in the query.
A test database has been created as follows:
create database commerce;
use commerce;
create table customers (id int);
insert into customers values (1000), (1001);
How do I refactor the error messages into a oneliner?:
if (result == NULL) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); }
FAIL_IF (result == NULL, "An error was encountered.");
I am looking for something like FAIL_IF (result == NULL, sprintf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)));