dongtuan1594
2014-04-18 21:45
浏览 45
已采纳

用双引号字段括起来的cvs加载数据INFILE

So, I got this. Just trying to insert a csv file into a MySQL through PHP PDO driver:

<?php
$databasehost = "localhost";
$databasename = "db";
$databasetable = "table";
$socketPath = "/home/mysql/mysql.sock";
$databaseusername="user";
$databasepassword = "pass";
$fieldseparator = ",";
$fieldenclosed = '"';
$lineseparator = "
";
$csvfile = "file.csv";

if(!file_exists($csvfile)) {
    die("File not found. Make sure you specified the correct path.");
}

try {
    $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename;unix_socket=$socketPath",
        $databaseusername, $databasepassword,
        array(
            PDO::MYSQL_ATTR_LOCAL_INFILE => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
    );
} catch (PDOException $e) {
    die("database connection failed: ".$e->getMessage());
}

$affectedRows = $pdo->exec("
    LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
    FIELDS TERMINATED BY ".$pdo->quote($fieldseparator).", ENCLOSED BY ". $pdo->quote($fieldenclosed)."
    LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES;");

echo "Loaded a total of $affectedRows records from this csv file.
";

?>

The csv file is something like this(comma separated and enclosed by double quotes).

"X410","","4114068500","000010","04/15/2014","04/16/2015"
"X410","","4220521243","000030","04/08/2014","04/08/2015"
"X410","","4130003659","000010","04/02/2014","04/05/2014"
"X410","","4220524277","000010","04/08/2014","04/08/2015"
"X410","","4114038136","000010","04/07/2014","04/07/2015"
"X410","","4130003594","000110","03/14/2014","03/14/2015"
"X410","","4130003675","000010","04/04/2014","04/04/2015"
"X410","","4130003623","000010","03/12/2014","03/12/2015"
"X410","","4130003679","000010","04/09/2014","04/09/2015"
"X410","","4130003679","000020","04/09/2014","04/09/2015"

THe ENCLOSED BY part is the one that's giving me trouble, I've done my homework and tried $fieldenclosed = '\"\"', $fieldenclosed = "\"\"", with and withouth the $pdo->quote($fieldenclosed) and any other weird concat stuf I've though of or found out in other topics with similar issues.

MySQL throws this error:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ' ENCLOSED BY '"'
LINES TERMINATED BY '
' IGNORE 1 LINES' at line 2' in /root/csvUpload.php:32

Im running MySQL 5.1 in a CentOS 6.4 server.

Any ideas?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题