参考:http://kevin850115.iteye.com/blog/578142
MySQL官网:http://dev.mysql.com/doc/refman/5.7/en/load-data.html
学弟有个面试题,在群里问了下如何将excel文件导入到数据库。以前也没试过,正好在学习MySQL,练练手吧。
首先,将excel文件另存为用逗号分隔的csv文件,传到linux服务器上,假设叫做test.csv。
用sed命令将第一行的列名称去掉sed -i '1p' test.csv
然后建库建表的命令的就得手工进行了,根据具体的表结构,大致命令如下:
> CREATE DATABASE `demo`;
> USE demo;
> CREATE TABLE `tb1` (
`id` int(4) NOT NULL PRIMARY KEY ,
`Name` char(10) DEFAULT NULL,
`Age` smallint(3) DEFAULT NULL,
`Sex` varchar(10) DEFAULT NULL,
`Mobile` bigint(15) DEFAULT NULL,
`Touzijingli` varchar(10) DEFAULT NULL,
`Job` varchar(10) DEFAULT NULL,
`Uname` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
(随便测试的,因此字段类型选择有点随意,请大家无视)
> desc tb1;
确保表结构和我们的原始EXCEL 的一致后,可用执行导入数据操作了,如下:
> load data local infile
terminated by ','
optionally enclosed by '"'
escaped by '"'
lines terminated by '\r\n';
参数说明:
terminated by 跟的是字段间的分隔符。
optionally enclosed by '"' 的意思就是无视这些个双引号
escaped by 字符转义,默认的是反斜杠(backslash:\ )
lines terminated by '\r\n'; 换行标志。windows下的换行是\r\n
官网更详细的格式如下:
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
[REPLACE | IGNORE]
INTO TABLE tbl_name
[PARTITION (partition_name,...)]
[CHARACTER SET charset_name]
[{FIELDS | COLUMNS}
[TERMINATED BY 'string']
[[OPTIONALLY] ENCLOSED BY 'char']
[ESCAPED BY 'char']
]
[LINES
[STARTING BY 'string']
[TERMINATED BY 'string']
]
[IGNORE number {LINES | ROWS}]
[(col_name_or_user_var,...)]
[SET col_name = expr,...]
http://blog.51cto.com/lee90/1825297