如何使用LOAD INFILE更新表?

时间:2018-10-03 09:56:14

标签: php mysql codeigniter

$this->db->query("LOAD DATA LOCAL INFILE '".$file_path."' 

        INTO TABLE table1
        CHARACTER SET  utf8mb4
        FIELDS TERMINATED BY ','

        OPTIONALLY ENCLOSED BY  '\"' 
        LINES TERMINATED BY '\r\n' 

        IGNORE 1 LINES 

        (Email,Jurisdiction_Parish,Jurisdiction_Ward,Jurisdiction_Precinct,Personal_FirstName,
        Personal_MiddleName,Personal_LastName,Personal_NameSuffix,Residence_HouseNumber,Residence_HouseFraction,Residence_StreetDirection,
        Residence_StreetName,Residence_ApartmentNumber,Residence_City,Residence_State,Residence_ZipCode5,Residence_ZipCode4,Mail_Address1,
        Mail_Address2,Mail_City,Mail_State,Mail_ZipCode5,Mail_ZipCode4,Mail_Country,Personal_Sex,Personal_Race,Registration_PoliticalPartyCode,
        Personal_Age,Registration_VoterStatus,Registration_Date,Registration_Number,Personal_Phone,LastVoted,Residence_WalkListOrder,
        Favorability,Yard_Sign,Comments,Personal_NameOrder,voted,Rating,Custom_Variable1,Custom_Variable2,Custom_Variable3)
        SET cid =".$cid.", csvsheet_id=".$csvsheet_id
        );

以上代码用于将CSV数据插入数据库,但是我想从CSV更新数据库的现有记录。因此,我该如何修改查询,以使其可用于更新记录。

2 个答案:

答案 0 :(得分:0)

  1. 您必须为字段定义主键或唯一键,以确保记录的相等性
  2. 您必须在REPLACE语句中添加LOAD INFILE关键字
LOAD DATA LOCAL INFILE 'myfile' 
  REPLACE
  INTO TABLE table1
  CHARACTER SET  utf8mb4
  ................

答案 1 :(得分:0)

我使用以下代码更新数据库的现有记录。

 LOAD DATA LOCAL INFILE 'myfile' 
 REPLACE
 INTO TABLE table1
 CHARACTER SET  utf8mb4

但是问题是我的CSV文件中只有两列。当我运行查询时,它更新了记录(仅投票列),但其他列已被清空。还要给所有列名加上数据也是.. ??