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

shell

创建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<len;i=`expr $i+1`))
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
“张三”
“李四”
“王五”
“赵六”

person

 

 

 

如果发现下载不了或者地址失效,请联系客服QQ: 2323178881
找资料 » shell脚本读取json文件数据存储到数据库

提供最优质的资源集合

立即查看 了解详情