【发布时间】:2023-04-08 04:42:02
【问题描述】:
我在导入超过 1,00,000 行的 CSV 文件时遇到问题。我正在使用fgetcsv 从 CSV 文件中获取数据。
我的要求是首先截断表,从 CSV 文件中获取数据并将其存储在数据库中。但每次它只获取 40000 到 50000 行。谁能建议我这是什么问题?我的代码如下,
$destination = realpath('../../admin/webroot/');
$originalPath = $destination."/".$this->request->data['Importmodel']['importfile'];
# Get Table Fields
$tableFields = ClassRegistry::init('Systemoption')->getTableDetails($this->request->data['Importmodel']['modeloptions']);
ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->query("TRUNCATE TABLE " . $this->request->data['Importmodel']['modeloptions']);
$row = 1;
if(($handle = fopen($originalPath, "r")) !== false) {
try {
while (($data = fgetcsv($handle, 0, "|")) !== false) {
$num = count($data);
if($num != (count($tableFields) - 1)) {
unlink($originalPath);
$this->Session->setFlash("Table \"".$this->request->data['Importmodel']['modeloptions']."\" fields and \"".$fileName."\" fields does not match", 'default', array('class'=>'flash_bad'));
$this->redirect(array('action' => 'index'));
exit;
}
$queryData = array();
for ($c=0; $c < $num; $c++) {
$queryData[$this->request->data['Importmodel']['modeloptions']][$tableFields[$c+1]] = $data[$c];
}
ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->create();
ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->save($queryData);
$row++;
}
$result = 1;
} catch (Exception $e) {
$result = 0;
}
}
if($result == 1) {
unlink($originalPath);
$this->Session->setFlash("Table \"" . $this->request->data['Importmodel']['modeloptions'] . "\" data populated successfully", 'default', array('class'=>'flash_good'));
$this->redirect(array('action' => 'index'));
exit;
} else {
$this->Session->setFlash("Error : Table \"" . $this->request->data['Importmodel']['modeloptions'] . "\" data not fully populated", 'default', array('class'=>'flash_bad'));
$this->redirect(array('action' => 'index'));
exit;
}
【问题讨论】:
-
如果要将数据从 CSV 文件导入 MySQL 表,最好的选择是使用
LOAD DATA INFILE。见reference -
错误日志中有什么内容?你的记忆力和时间限制是多少?
-
@Mike W:我不能使用 LOAD DATA INFILE,因为我只需要 CSV 中的一些列。所以,我不能用那个
-
@Maerlyn:我没有收到任何错误。内存大小为3000M,时间限制为10000000。
-
@hardcoderwithmilestone 你可以使用
LOAD DATA INFILE。您必须为输入文件中的每个字段分配一个目标,但您可以将不需要的字段分配给虚拟变量并丢弃它们。您还可以在将数据分配给表中的列之前使用变量来操作数据。
标签: php mysql cakephp csv fgetcsv