shell脚本读取json文件数据存储到数据库

创建json文件test.json

[
{“id”:1,”name”:”张三”,”age”:20,”sex”:”F”,”hobby”:”游泳”},
{“id”:2,”name”:”李四”,”age”:21,”sex”:”M”,”hobby”:”上网”},
{“id”:3,”name”:”王五”,”age”:22,”sex”:”F”,”hobby”:”游戏”},
{“id”:4,”name”:”赵六”,”age”:23,”sex”:”M”,”hobby”:”冲浪”}
]

创建shell脚本jq_mysql.sh

#!/bin/bash
USER=”root”
DATABASE=”people”
TABLE=”person”
mysql -u $USER << EOF 2>/dev/null
CREATE DATABASE $DATABASE
EOF
[ $? -eq 0 ] && echo “created DB” || echo DB already exists

mysql -u $USER $DATABASE << EOF 2>/dev/null
CREATE TABLE $TABLE(
id int,
name varchar(100),
age int,
sex varchar(4),
hobby varchar(100)
);
EOF
[ $? -eq 0 ] && echo “Created table success” || echo “Table already exist”

array=()

len=`cat test.json | jq ‘. | length’ `

echo “数组节点的长度:”$len
for (( i=0;$i do

ID=`cat test.json | jq ‘.[‘$i’].id’`
NAME=`cat test.json | jq ‘.[‘$i’].name’`
AGE=`cat test.json | jq ‘.[‘$i’].age’`
SEX=`cat test.json | jq ‘.[‘$i’].sex’`
HOBBY=`cat test.json | jq ‘.[‘$i’].hobby’`
mysql -u $USER $DATABASE << EOF 2>/dev/null
INSERT INTO $TABLE VALUES ($ID,$NAME,$AGE,$SEX,$HOBBY)
EOF
[ $? -eq 0 ] && echo “Insert data success” || echo “Insert data fail”

arr[${#arr[*]}]=`cat test.json | jq ‘.[‘$i’].name’`
done

for a in ${arr[*]}
do
echo $a
done

 

执行sh jq_mysql.sh

运行结果:

created DB
Created table success
数组节点的长度:4
Insert data success
Insert data success
Insert data success
Insert data success
“张三”
“李四”
“王五”
“赵六”

shell脚本读取json文件数据存储到数据库_第1张图片

你可能感兴趣的:(后端)