使用shell脚本将CSV文件上载到数据库中

时间:2015-06-06 12:03:09

标签: mysql bash shell csv

我使用脚本上传csv文件

 export IFS=","
 cat  $_csv_files | read a b c d;

现在,我需要将csv文件的 c 列中的值插入到我的数据库中制造地图表的制造商名称列中我将如何实现这一目标?

当我尝试下面的代码时

mysql -u $_db_user -p$_db_password $_db << eof
    INSERT INTO \`manufacturemap\`
    ( \`manufacture_name\`) VALUES ($c)
eof

我明白了:

 ERROR 1136 (21S01) at line 1: Column count doesn't match value count at row 1

过去几个小时我一直被困在这里,请帮助我。

输入(csv文件):

    a,b,c,d
1.01100156278101E+15,2014/07/08,2014/07/08,"Cash Withdrawal by Cheque-173320--TT1421957901"
1.01100156278101E+15,2014/07/08,2014/07/08,"Cheque Paid-173261--TT1421951241"
1.01100156278101E+15,2014/07/08,2014/07/08,"Cheque Paid-173298--TT1421951226"
1.01100156278101E+15,2014/06/08,2014/06/08,"Cash Withdrawal by Cheque-173319--TT1421858465"

1 个答案:

答案 0 :(得分:1)

试试这个:

#! /bin/sh

values ()
{
    cat "$@" | \
    while IFS=, read -r a b c d; do
        printf '%s\n' "$c"
    done | \
    paste -sd, -
}

printf 'INSERT INTO `manufacturemap` (`manufacture_name`) VALUES (%s)\n' "$(values $_csv_files)" | \
    mysql -u"$_db_user" -p"$_db_password" "$_db"