我需要将 100 多个 CSV 文件加载到 MySQL 中,因此我正在编写一个脚本来执行此操作。除此之外,我有以下代码片段,它导入每个 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]} — {$errorInfo[2]} ({$errorInfo[1]})</p>$queryString";
最佳答案
一个或多个文件包含 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 的帖子中,我发现 this关于准备功能和加载数据。
关于php - 使用 PDO 加载 CSV 文件会导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21830978/