当前位置: 移动技术网 > 网络运营>服务器>Linux > shell简单处理mysql查询结果的方法

shell简单处理mysql查询结果的方法

2018年08月08日  | 移动技术网网络运营  | 我要评论

首先理清要了解shell脚本的数组与字符串的一些特性:

str=("hello" "world" "!") #结果: str: 3 #普通的字符串数组
echo "str: " ${#str[@]}
str1=("hello world !") #结果: str1: 1 #普通的字符串数组
echo "str1: "${#str1[@]}
str2=(`echo "hello world !"`) #结果: str2: 3 #等价于 str
echo "str2: " ${#str2[@]} 


function strdeal(){
  param=("$@")
  echo ${param[@]}
  echo $1
  echo $2
  echo $3
}
echo "-----------first----------------"
strdeal "hello world !" 
echo "-----------second----------------"
strdeal "hello" "world" "!"
echo "-----------third----------------"
strdeal $str1  #等价于second

用mysql自带数据库world.city为例来展示处理查询结果

#!/bin/sh
#filename:demo.sh
cityres=""
citycolnum=5
function getcurvalue(){
  curvalue=""
  colindex=$1
  rowindex=$2
  idx=$[$citycolnum*$colindex+$rowindex-1]  #通过行列进行计算目标位置
  if [ $idx -le ${#cityres[@]} ] ;then
    echo ${cityres[$idx]} #获取目标结果
  fi
}

#获取city表总行数
function getcityrownum(){
  echo $[${#cityres[@]}/$citycolnum-1]
}


cityres=(`mysql -uroot -p123456 world -e "select * from city"`)  #查询结果以数组来保存,等价于上面的str2
curvalue=`getcurvalue $1 $2`  #$1为行数 $2为列数
echo $curvalue
rownum=`getcityrownum` #获取总行数
echo $rownum

调用示例

sh demo.sh 1 2

注意的事项

getcityrownum后的记录数与实际的记录数并不一致,这是由于city表name 或者district字段中由于多个字符串组成,如:andorra la vella

这样就会占用3个位置。

以上这篇shell简单处理mysql查询结果的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网