用于加载数据 Infile MySQL 的 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22137390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:46:56  来源:igfitidea点击:

Bash Script for Load Data Infile MySQL

mysqlbasheofload-data-infile

提问by XFerrariX

So i'm trying to create a script that I can run that will do a batch import of csv files into a table.

因此,我正在尝试创建一个可以运行的脚本,该脚本会将 csv 文件批量导入到表中。

I'm having trouble getting the script to work.

我在让脚本工作时遇到问题。

Here is the script i'm running:

这是我正在运行的脚本:

#!/bin/bash
for f in *.csv
do
"/opt/lampp/bin/mysql -e use test -e LOAD DATA LOCAL INFILE ("$f") INTO TABLE temp_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (DATE, TIME, SITE_NAME, SITE_IP, TOTAL_TALKTIME, EDGE_UL_BYTES, EDGE_DL_BYTES);"
done

When I run the script I receive the following error message:

当我运行脚本时,我收到以下错误消息:

./script.sh: line 5: unexpected EOF while looking for matching `''
./script.sh: line 7: syntax error: unexpected end of file

The load data local infile command works fine directly in mysql.

load data local infile 命令可以直接在 mysql 中正常工作。

回答by that other guy

When you want to use literal double quotes in double quoted strings, escape them with \". Since mysql doesn't care about line feeds, you can also break the line to make it more readable:

当您想在双引号字符串中使用文字双引号时,请使用\". 由于 mysql 不关心换行符,您还可以断行以使其更具可读性:

#!/bin/bash
for f in *.csv
do
/opt/lampp/bin/mysql -e "use test" -e "
      LOAD DATA LOCAL INFILE '$f'
      INTO TABLE temp_table 
      FIELDS TERMINATED BY ',' 
      OPTIONALLY ENCLOSED BY '\"' 
      LINES TERMINATED BY '\n' 
      IGNORE 1 LINES 
      (DATE, TIME, SITE_NAME, SITE_IP, TOTAL_TALKTIME, 
           EDGE_UL_BYTES, EDGE_DL_BYTES);"
done

回答by vishu9219

mysql -u<username> -p<password> -h<hostname> <db_name> --local_infile=1 -e "use <db_name>" -e"LOAD DATA LOCAL INFILE '<path/file_name>' 
IGNORE INTO TABLE <table_name>
FIELDS TERMINATED BY '\t'
OPTIONALLY ENCLOSED BY '\"'"