使用PDO加载CSV文件会导致语法错误

时间:2014-02-17 13:57:46

标签: php mysql csv pdo

我需要在MySQL中加载100多个CSV文件,因此我编写了一个脚本来执行此操作。除此之外,我还有以下代码片段,它导入每个CSV文件:

    private function importFile(){
    if($this->connection->beginTransaction()){
        $transactionFailed = false;
        $importStatement = $this->connection->prepare("
            LOAD DATA INFILE :file
            REPLACE INTO TABLE :table;
        ");
        foreach($this->fetchFileList() as $file){
            $executeSuccesfull = $importStatement->execute(array(
                ':file' => $this->path . DIRECTORY_SEPARATOR . $file,
                ':table' => $file
            ));
            if(!$executeSuccesfull){
                $transactionFailed = true;
                $this->fetchDBError($importStatement);
                $this->connection->rollBack();
                break;
            }
        }

        if(!$transactionFailed){
            $this->connection->commit();
        }
    }
    else{
        $this->fetchDBError();
    }
}

$this->path指向所有CSV文件所在的路径(我检查过)。每个$file都与其导入数据的表具有完全相同的名称,没有文件扩展名(其中任何一个都没有.csv)。我使用的是运行在Windows XP之上的PHP 5.3.9,MySQL 5.0.27。所有这些都在我的本地机器上运行。

问题是,我发现了以下错误:

[ERROR 42000] — You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
''the_first_file'' at line 2 (1064)

The query issued was:

            LOAD DATA INFILE :file
            REPLACE INTO TABLE :table;

此代码是由我班级的另一种方法生成的:

    private function fetchDBError($statement = null){
    $errorCode = null;
    $errorInfo = null;
    $queryString = '';
    if($statement){
        $errorInfo = $statement->errorInfo();
        $errorCode = $statement->errorCode();
        $queryString = "<p>The query issued was:</p><pre>{$statement->queryString}</pre>";
    }
    else{
        $errorInfo = $this->connection->errorInfo();
        $errorCode = $this->connection->errorCode();
    }
    $this->success = false;
    $this->message = "<p>[ERROR $errorCode] {$errorInfor[0]} &mdash; {$errorInfo[2]} ({$errorInfo[1]})</p>$queryString";

1 个答案:

答案 0 :(得分:0)

一个或多个文件包含aphostophe,请尝试使用:

      $filepath = $this->path . DIRECTORY_SEPARATOR .  str_replace("'", "''", $file);

然后在查询参数中使用$ filepath。

这是mysql加载数据函数的一个例子:

LOAD DATA INFILE '$filepath' INTO TABLE test
FIELDS TERMINATED BY ',';

还尝试指定FIELDS TERMINATED BY。

在stackoverflow帖子中,我找到了关于准备功能和LOAD DATA的this