doudun2212
doudun2212
2018-07-11 13:06

Yii2 LOAD DATA LOCAL INFILE

已采纳

I know there are other solutions to this problem, but it did not work for me.

I am trying to execute a LOAD DATA LOCAL INFILE statement in a MySQL database via a Yii2 website. I have got this working in the past, so I am not sure why it doesn't work anymore.

I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1148 The used command is not allowed with this MySQL version

I do have the following setting in my db.php config file.

'attributes' => [ PDO::MYSQL_ATTR_LOCAL_INFILE => true ],

I also tried disabling secure-file-priv to no avail.

EDIT

I tried running the following query from Workbench and it throws an error via Workbench as well. However, it works on MySQL 5.7. I am currently using 8.0

LOAD DATA LOCAL INFILE 'D:/Temp/6_attlog.dat' IGNORE
INTO TABLE att_log
FIELDS TERMINATED BY '\t' ENCLOSED BY '''' LINES TERMINATED BY '
' IGNORE 0 LINES 
(@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) SET `id` = TRIM(@id)

EDIT 2

I got it to work with "LOAD DATA INFILE"...

...but it does not work with "LOAD DATA LOCAL INFILE"

Here's the code I was using...

$inFile = str_replace('\\', '/', realpath('uploads/'.$model->file->name));
Yii::$app->db->createCommand('
    LOAD DATA LOCAL 
    INFILE \''.$inFile.'\' IGNORE 
    INTO TABLE att_log 
    FIELDS TERMINATED BY \'\\t\'  
    ENCLOSED BY \'\'\'\' 
    LINES TERMINATED BY \'
\' 
    IGNORE 0 LINES 
    (@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) 
    SET `id` = TRIM(@id)
')->execute();
unlink($inFile);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanmei1350 duanmei1350 3年前

    According to MySQL documentation, server needs to be configured to allow LOCAL keyword:

    LOCAL works only if your server and your client both have been configured to permit it. For example, if mysqld was started with the local_infile system variable disabled, LOCAL does not work.

    https://dev.mysql.com/doc/refman/8.0/en/load-data.html

    Are you sure that your server is correctly configured to allow this keyword?

    点赞 评论 复制链接分享
  • doujiang7258 doujiang7258 3年前

    Just a suggestion

    in PHP you can use single and double quote so you could build you command in a simple an more clear way eg:

      $inFile = str_replace('\\', '/', realpath('uploads/'.$model->file->name));
      Yii::$app->db->createCommand("
          LOAD DATA LOCAL 
          INFILE '".$inFile."' IGNORE 
          INTO TABLE att_log 
          FIELDS TERMINATED BY '\t'  
          ENCLOSED BY '\' 
          LINES TERMINATED BY '
    \' 
          IGNORE 0 LINES 
          (@id, `date_time`, `dev_id`, `mode`, `work_code`, `work_code1`) 
          SET `id` = TRIM(@id)
      ")->execute();
      unlink($inFile);
    
    点赞 评论 复制链接分享

相关推荐