mysql根据条件将文本数据插入数据库
data.txt
7 jerry 1991-12-13 man 8 mike 1991-12-13 women 9 tracy 1991-12-13 man 10 kobe 1991-12-13 man 11 allen 1991-12-13 women 12 curry 1991-12-13 man 13 tom 1991-12-13 women
db_import.sh
#!/bin/bash # db_user="teacher" db_password="123456" mysql_conn="mysql -uteacher -p$db_password" cat data.txt | while read id name birthday sex do if [ $id -gt 10 ];then $mysql_conn -e "insert into student.class values($id,'$name','$birthday','$sex')" fi done
将data.txt和db_import.sh放到同一个目录,命令行执行下面命令
sh db_import.sh
其他:如果文本中的分割符不是空格,是“|”,则在脚本加一行IFS=|(默认分割符为空格和table)
data2.txt
7|jerry|1991-12-13| man 8|mike|1991-12-13|women 9|tracy|1991-12-13|man 10|kobe|1991-12-13|man 11|allen|1991-12-13|women 12|curry|1991-12-13|man 13|tom|1991-12-13|women
db_import2.sh
#!/bin/bash # db_user="teacher" db_password="123456" mysql_conn="mysql -uteacher -p$db_password" IFS=| cat data.txt | while read id name birthday sex do if [ $id -gt 10 ];then $mysql_conn -e "insert into student.class values($id,'$name','$birthday','$sex')" fi done