嘿伙计们,你可以看到我有这个PHP脚本:
<?php
$databasehost = "localhost";
$databasename = "";
$databasetable = "";
$databaseusername="";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$enclosedbyquote = '"';
$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",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$pdo->exec("TRUNCATE TABLE `$databasetable`");
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable`
FIELDS OPTIONALLY ENCLOSED BY ".$pdo->quote($enclosedbyquote)."
TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)."
IGNORE 1 LINES");
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
现在你可以看到这是将csv文件导入我的数据库并截断整个SQL表。
我的问题是如何阻止表格的第一列受到导入的影响?我将使用第一列作为ID,任何想法我怎么能这样做?
由于
答案 0 :(得分:0)
简单。而不是:
TRUNCATE TABLE `$databasetable`
使用:
UPDATE `$databasetable` SET colB = '', colC = '', colD = '', colE = '';
其中colA是您要保留的列。如果您使用的是NULL字段,请更改为:
UPDATE `$databasetable` SET colB = NULL; #etc.