pythonmysqlcsvmampload-data-infile

How can you replace NA values with NULL while inserting data from a file to a table?


I am attempting to import data from a csv file into an existing table in my database. It seems to be working fine, except that mysql does not accept NA as a value for columns represented by an int. Therefore I would like to change the values of NA to NULL while importing the file. Also, I would like to terminate a row from the table that uses NA as a primary key. This would all be easy to change if the values were already in the database table, however the values are not getting added due to this error. For the record I use MAMP.

Down below is the code I currently use:

LOAD DATA LOCAL INFILE 'filename.csv' 
INTO TABLE table_name 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
IGNORE 1 ROWS

Solution

  • As we know nothing about your table or your csv lets assume you have 4 columns and you want to replace columns2 NA with NULL

    LOAD DATA LOCAL INFILE 'filename.csv' 
    INTO TABLE table_name 
    FIELDS TERMINATED BY ',' 
    ENCLOSED BY '"' 
    IGNORE 1 ROWS
    (column1, @int, column3, column4)
    SET column2 = IF(@int = 'NA',NULL,@int);