mysql terminated_LINES TERMINATED BY和FIELDS TERMINATED BY的多种可能性 - MySQL

bd96500e110b49cbb3cd949968f18be7.png

I'm trying to create a feature in my Content Management System in which users can upload a CSV file which is then parsed and the data is put in a MySQL database. To do this I use a file input and this SQL query.

$sql = "LOAD DATA LOCAL INFILE '".$_FILES["file"]["tmp_name"]."'

INTO TABLE persons

FIELDS TERMINATED BY ';'

LINES TERMINATED BY '\r'

(id, name, email, contacts)";

This works perfectly for a .csv file I created on my computer, but not al CSV files have fields that are terminated by a semicolon and have lines that are terminated with a \r. Now I want this query to work for all .csv files. Otherwise this feature won't work well enough to be implemented in my CMS. Is there any way I can make this work for .csv files which have other field and line endings? (e.g \n, \r\n, ,)

解决方案

Try LINES TERMINATED BY '\r\n'

This will work for files ending lines with '\r\n', but also with '\r' and '\n'. From the MySQL docs:

The FIELDS TERMINATED BY, LINES STARTING BY, and LINES TERMINATED BY

values can be more than one character. For example, to write lines

that are terminated by carriage return/linefeed pairs, or to read a

file containing such lines, specify a LINES TERMINATED BY '\r\n'

clause.

[EDITED]

You also need to add \r\n to the clause FIELDS TERMINATED BY in order to tell the parser not to include the end-of-lines symbols in the last field of the first line. So

FIELDS TERMINATED BY ';, \t\r\n'

will work in most cases.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值