shell 导入csv到mysql

方法一:整个文件导入

#/bin/bash
export_sql="LOAD DATA INFILE '$1'
            INTO TABLE $3
            CHARACTER SET utf8
            FIELDS TERMINATED BY ','
            ENCLOSED BY '\"' "
mysql -h127.0.0.1 -P3306 -uroot -proot $2 -e "${export_sql}"

执行:

[root@xiaofei ~]# /home/xiaofei/test/test.sh  /usr/soft/t_config.csv psi t_config

方法二:一行一行读取然后导入

shell脚本内容如下

#!/bin/sh
#The username of mysql database
USER="root"

#The password of mysql database
PASS="dragonwake"

#The datebase name will be created
DATABASE="SmartCare"

TABLE="sct_Province"

TABLE_DATA="prov.csv"

if [ -f ${TABLE_DATA} ]; then
	
	echo "File ${TABLE_DATA} Existed."
	
else 
	
	echo "File ${TABLE_DATA} Not Existed."
	echo 
	exit 2

fi

while read line;
do

	query=`echo $line | awk -F, '{printf("\"%s\", \"%s\", \"%s\", \"%s\"", $2, $3, $4, $5)}'`
	statement=`echo "insert into ${TABLE}(ProvinceCode, ParentID, ProvinceName, Level) values($query)"`
	echo $statement
	
mysql -u $USER -p$PASS $DATABASE << EOF > /dev/null
	insert into ${TABLE}(ProvinceCode, ParentID, ProvinceName, Level) values($query);
EOF
	
done < $TABLE_DATA

if [ $? -eq 0 ]; then
	
	echo "Insert Data Into $TABLE Success."
	
fi

注:如果csv是从windows系统上传的 要去改下编码方式     window一般是doc     先用vi打开csv文件   然后   :set  ff?  查看是否是unix   不是的话    :set ff=unix    然后wq保存退出

你可能感兴趣的:(shell)