I have C code (gcc) using the mysql.h library to insert data in a database table:
/* Insert event */
void insert_event (MYSQL *conn, char *event, char *date) {
char insert_query[99];
if (!strcmp(event, "final")) {
snprintf(insert_query, sizeof(insert_query), "insert into events values ('%s', NULL);", event);
} else {
snprintf(insert_query, sizeof(insert_query), "insert into events values ('%s', '%s');", event, date);
}
mysql_query(conn, insert_query);
}
Data would look something like this
event date
----- ----
A 2023-12-01
B 2024-01-11
C 2024-01-22
final
The question is whether the above code can be refactored, since my current code (consisting of about 20 fields) differs only by this one date field.
I was hoping to turn the whole if-block into something as follows:
snprintf(insert_query, sizeof(insert_query), "insert into events values ('%s', '%s');", event, (strcmp(event, "final")) ? date : NULL);
This will not work, as NULL values are not to be quoted. Perhaps there is a more elegant solution?