我有一个包含10列的CSV文件。我只想从该文件中选择一些列,然后使用LOAD DATA INFILE
命令将它们加载到MySQL数据库中。
Answers:
将数据加载到MySQL中的表中并指定列:
LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;
@ col1,2,3,4是用于保存csv文件列(假设为4)的变量,id是表列。
for i in range(1,100): print("@column",i,",",end="",sep="")
LOAD DATA INFILE 'file.csv'
INTO TABLE t1
(column1, @dummy, column2, @dummy, column3, ...)
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';
只需将column1,column2等替换为您的列名,然后将@dummy放在CSV中有您要忽略的列的位置。
详细信息在这里。
(field,names)
分号放在最后,以使其起作用。
在加载数据infile语句中指定CSV中的列名称。
代码是这样的:
LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);
在这里,您只向表的两列添加数据(可以使用列名选择它们)。
您唯一需要注意的是,您有一个CSV文件(filename.csv),每行(行)有两个值。否则请提及。我有不同的解决方案。
谢谢。
例:
ae.csv文件的内容:
"Date, xpto 14"
"code","number","year","C"
"blab","15885","2016","Y"
"aeea","15883","1982","E"
"xpto","15884","1986","B"
"jrgg","15885","1400","A"
CREATE TABLE Tabletmp (
rec VARCHAR(9)
);
仅放置第3列:
LOAD DATA INFILE '/local/ae.csv'
INTO TABLE Tabletmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 2 LINES
(@col1, @col2, @col3, @col4, @col5)
set rec = @col3;
select * from Tabletmp;
2016
1982
1986
1400
如果数据库表中的列数多于csv中的列数,则可以这样进行:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
对于那些具有以下错误的人:
错误代码:1290。MySQL服务器正在使用--secure-file-priv选项运行,因此它无法执行此语句
您只需运行此命令即可查看哪个文件夹可以从中加载文件:
SHOW VARIABLES LIKE "secure_file_priv";
之后,您必须复制该文件夹中的文件,然后使用LOAD DATA LOCAL INFILE
代替来运行查询LOAD DATA INFILE
。
ERROR 1148 (42000): The used command is not allowed with this MySQL version
。