Ad

What String Should I Use To Compare With A Mysql Entry Which Is NULL In C

- 1 answer

My problem is that I'm developing a C program which reads integers from a mysql table (which are stored as INT) and do some calculation and INSERT them to another table which is in a another server running ORACLE DB. Here is part of my code I used to do so. Only a code segment is given which I thought has the issue.

char sqlPlusString[300];
memset(sqlPlusString, 0, 300);
int i, sum = 0;
int p1_2weeks = 0, p2_1month = 0, p3_2month = 0;
while (row = mysql_fetch_row(result)) {
    int i = 1, sum = 0;
    memset(sqlPlusString, 0, 300);

    for (i = 1; i < 32; i++) {
        if (strcmp(row[i], "NULL") == 0) {
            sum = sum + 0; 
        } else
            sum = sum + strtol(row[i], NULL, 10);

hope you could understand what I am saying. The thing is when I try to do this it gives a segmentation fault. I guessed it may be because the comparison gives another result. But it wasn't, It clearly returns a zero when the string "NULL" is there. could there be some other thing to represent NULL values in Mysql DBs. Could someone please explain me.

Ad

Answer

You cannot check for NULL values in the database by comparing with "NULL". NULL values are actually returned as NULL pointers in the corresponding columns. Modify your code this way:

while ((row = mysql_fetch_row(result)) != NULL) {
    int i, sum = 0;
    memset(sqlPlusString, 0, 300);

    for (i = 1; i < 32; i++) {
        if (row[i] != NULL) {
            sum += strtol(row[i], NULL, 10);
        }
    }
    ...
}

Check the manual page http://dev.mysql.com/doc/refman/5.7/en/mysql-fetch-row.html for more details.

Ad
source: stackoverflow.com
Ad