Please read the documentation for LOAD DATA INFILE;它是加载数据的好选择,即使是非常大的文件。引用Reference manual: Speed of insert statements:
从文本文件加载表格时,使用LOAD DATA INFILE。这通常比使用 INSERT 语句快 20 倍
假设您的表比.csv 文件的列多,那么您必须编写如下内容:
load data local infile 'path/to/your/file.csv'
into table yourTable
fields terminated by ',' optionally enclosed by '"' lines terminated by '\n'
ignore 1 lines -- if it has column headers
(col1, col2, col3, ...) -- The matching column list goes here
见my own question on the subject and its answer。
另外,如果您需要更快的插入,您可以:
- 忽略外键约束,在执行
load data之前使用SET foreign_key_checks = 0;,和/或
- 在执行
load data之前用alter table yourTable disable keys;禁用表的索引,然后用alter table yourTable enable keys;重建它们
未经测试:如果您的.csv 文件的列比您的表多,我认为您可以将文件中的“超出”列分配给临时变量:
load data local infile 'path/to/your/file.csv'
into table yourTable
fields terminated by ',' optionally enclosed by '"' lines terminated by '\n'
ignore 1 lines -- if it has column headers
(col1, col2, col3, @dummyVar1, @dummyVar2, col4) -- The '@dummyVarX` variables
-- are simply place-holders for
-- columns in the .csv file that
-- don't match the columns in
-- your table