简体   繁体   English

如何一次将大量数据插入mySQL数据库?

[英]How can I insert a lot of data into mySQL database at once?

I insert data from a text file into mySQL database and there will be inserted around 6000 or more entries at once. 我将文本文件中的数据插入到mySQL数据库中,一次插入大约6000个或更多条目。

try {
   $sql = "INSERT INTO data (id,name,date,place) values(?,?,?,?) ";
   $q = $pdo->prepare($sql);
   foreach($data as $row) {
      $q->execute(array($row['id'], $row['name'], $row['date'], $row['place']));
   }
}
catch (PDOException $pe) {
   echo $pe->getMessage();
}
catch (Exception $e ) {
   echo $e->getMessage();
}

I tried it with 3000 entries and everything works fine. 我尝试了3000条目,一切正常。 But if I have more data to be inserted it happens that my page is blank and nothing is inserted into my database. 但是,如果我要插入更多数据,则会发生我的页面空白并且没有任何内容插入到我的数据库中。

What could cause this problem and how can I solve it? 什么可能导致这个问题,我该如何解决?

Since you already have text file then use below query 由于您已经有文本文件,因此请使用以下查询

LOAD DATA INFILE 'file/path/to/file.txt' 
INTO TABLE table-name 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

Make sure your data in file is in sequence with your table rows. 确保文件中的数据与表行顺序一致。

Read more here https://dev.mysql.com/doc/refman/5.6/en/load-data.html 在这里阅读更多内容https://dev.mysql.com/doc/refman/5.6/en/load-data.html

Use mysql LOAD DATA INFILE 使用mysql LOAD DATA INFILE

refer to This Answer 请参阅本答案

If you use PDO or the like with looping, you are doing it wrong, and slow. 如果你使用PDO或类似的循环,你做错了,慢。

NSERT statements that use VALUES syntax can insert multiple rows. 使用VALUES语法的NSERT语句可以插入多行。 To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. 为此,请包含多个列值列表,每个列值都括在括号内并用逗号分隔。 Example: 例:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

From How to do a batch insert in MySQL 如何在MySQL中进行批量插入

Instead of running multiple queries inside a loop, you should use the multi-insert syntax. 您应该使用多插入语法,而不是在循环内运行多个查询。 Example: 例:

INSERT INTO data (id,name,date,place) VALUES (:id1,:name1,:date1,:place1), (:id2,:name2,:date2,:place2), (:id3,:name3,:date3,:place3);

Check out this article on doing multi-inserts with prepared statements. 查看有关使用预准备语句执行多插入的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM