在我的代码中,我有一个如下所示的查询:
$load_query = "LOAD DATA LOCAL INFILE '{$file}' INTO TABLE `{$table}`
FIELDS TERMINATED BY ',' ENCLOSED BY '\"';";
以下是我尝试加载的文件中包含的示例行:
"MC318199","06160","1","P","00750","00000","TN598792","04/16/2009","91X"
您会注意到在示例行的末尾有很多空格。这些空格都出现在终止该行的新行字符“\ n”之前。问题是这些空间会进入数据库。
运行LOAD DATA INFILE
命令时如何删除其他空格?有没有办法使用RTRIM
?
修改
由于 ajreal 建议我必须重新准备文件。准备好文件后,它正确地插入到数据库中。我修改了在http://gabeanderson.com/2008/02/01/unixlinux-find-replace-in-multiple-files/找到的bash脚本来完成此任务。代码如下所示:
#!/bin/bash
for fl in *.txt; do
mv $fl $fl.old
sed 's/[ \t]*$//' $fl.old > $fl
rm -f $fl.old
done
答案 0 :(得分:7)
$load_query = "LOAD DATA LOCAL INFILE '{$file}' INTO TABLE `{$table}`
FIELDS TERMINATED BY ',' ENCLOSED BY '\"' (col1, col2, ... , @col_with_spaces)
SET col_with_spaces = RTRIM(@col_with_spaces);";
这样您就不需要预处理文件,也不需要在表格上创建其他更新。
答案 1 :(得分:2)
如何在第二步中简单地修剪导入的数据?
$fix_query = "UPDATE `{$table}` SET LastFieldName = RTRIM(LastFieldName);";
答案 2 :(得分:2)
update $table set $last_column=rtrim($last_column);
或使用vi
(或任何编辑器)
或重新准备$ file
答案 3 :(得分:1)
使用LINES TERMINATED BY '\n'
$load_query = "LOAD DATA LOCAL INFILE '{$file}' INTO TABLE `{$table}`
FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' " ;