Search code examples
mysqlcload-data-infile

LOAD DATA in C The used command is not allowed


I have a problem with LOAD DATA in C.

When I execute the LOAD DATA command in the Command line it works just fine, but when I try the same thing in C it says:

The used command is not allowed with this MySQL version.

Here's my code:

    #include <my_global.h>
    #include <mysql.h>
    #include <stdio.h>

void finish_with_error(MYSQL *con)
{
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con);
    exit(1);
}

int main(int argc, char **argv)
{
    MYSQL *con = mysql_init(NULL);

    if (con == NULL)
    {
        fprintf(stderr, "%s\n", mysql_error(con));
        exit(1);
    }

    if (mysql_real_connect(con, "localhost", "", "", "testdb", 0, NULL, 0) == NULL)
    {
        finish_with_error(con);
    }else{
    printf("MySQL client version: %s\n", mysql_get_client_info());
    }



    if (mysql_query(con, "LOAD DATA LOCAL INFILE '/home/lien/Dropbox/StageTolsma/1eOpdracht/TxtBestanden/01_0021_200912100000.txt' INTO TABLE input FIELDS TERMINATED BY ';=' LINES TERMINATED BY '\n;'"))
    {
        finish_with_error(con);
    }else{
        printf("File was uploaded to the database\n");
    }

    mysql_close(con);
    exit(0);
}

Solution

  • Now it's working with change to explicitly set MYSQL_OPT_LOCAL_INFILE option.

    Useful links

    1. Security Issues with LOAD DATA LOCAL
    2. mysql_options()

    MYSQL_OPT_LOCAL_INFILE option info

    MYSQL_OPT_LOCAL_INFILE (argument type: optional pointer to unsigned int)
    
    If no pointer is given or if pointer points to an unsigned int that has a nonzero value, the LOAD LOCAL INFILE statement is enabled.
    

    so issue fixed by giving a null value ( equivalent to no pointer given ) :

    mysql_options(con, MYSQL_OPT_LOCAL_INFILE, 0);
    

    working code

    #include <my_global.h>
        #include <mysql.h>
        #include <stdio.h>
    
    void finish_with_error(MYSQL *con)
    {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }
    
    int main(int argc, char **argv)
    {
        MYSQL *con = mysql_init(NULL);
        mysql_options(con, MYSQL_OPT_LOCAL_INFILE, 0);  
    
        if (con == NULL)
        {
            fprintf(stderr, "%s\n", mysql_error(con));
            exit(1);
        }
    
        if (mysql_real_connect(con, "localhost", "", "", "testdb", 0, NULL, 0) == NULL)
        {
            finish_with_error(con);
        }else{
        printf("MySQL client version: %s\n", mysql_get_client_info());
        }
    
    
    
        if (mysql_query(con, "LOAD DATA LOCAL INFILE '/home/lien/Dropbox/StageTolsma/1eOpdracht/TxtBestanden/01_0021_200912100000.txt' INTO TABLE input FIELDS TERMINATED BY ';=' LINES TERMINATED BY '\n;'"))
        {
            finish_with_error(con);
        }else{
            printf("File was uploaded to the database\n");
        }
    
        mysql_close(con);
        exit(0);
    }