shell

shell.6.1 bash脚本:向数据库插入随机数据

 

脚本要求:
===========

数据库名:firstdb;
表名:class1;
字段:name,gender,age;

1>向表中插入100行数据,要求:
name:stu1-stu100
gender:随机为M或F
age:18到28之间的随机数;

2>以性别为分组,显示每组的平均年龄;

3>显示年龄小于等于25岁的性别是F的用户,并按年级的升序排列;

分析
=========
1>创建100个有规律的用户名,可以用循环语句就可以简单实现;

2>性别为随机的M或F:

生成100个随机数,用随机数对2取模,定义值为0,则取值M,否则就取值F;

rand=$[$RANDOM%2]

3>年龄取值为18到35之间的随机数:

$RANDOM : 取值范围是0-32767;

$RANDOM%18 : 取值范围是0-17;

$RANDOM%18+18 : 取值范围是18-35;

select  sum(age), count(*), gender, avg(age)  from  class1  group  by  gender;
select  *  from  class1  where  age<=25  and  gender=”F”  order  by  age;

脚本
============

#!/bin/bash
#

for ((i=1;i<=100;i++)); do
  stu_name=stu$i
  stu_gender=$[$RANDOM%2]
  stu_age=$[ $RANDOM%18 + 18 ]

  if [ $stu_gender -eq 0 ]; then
    
    mysql -uroot -h192.168.206.66 -pkou -e 'INSERT INTO firstdb.class1 (name,gender,age) VALUES ("'$stu_name'","F",'$stu_age');'
  else
    
    mysql -uroot -h192.168.206.66 -pkou -e 'INSERT INTO firstdb.class1 (name,gender,age) VALUES ("'$stu_name'","M",'$stu_age');'
  fi
done


avg_age=$(mysql -uroot -h192.168.206.66 -pkou -e 'select sum(age),count(*),gender,avg(age) from firstdb.class1 group by gender;')
view_age=$(mysql -uroot -h192.168.206.66 -pkou -e 'select * from firstdb.class1 where age<=25 and gender="F" order by age;')

echo "$avg_age"
echo
echo "$view_age"

脚本运行结果
——————

sum(age)	count(*)	gender	avg(age)
1191	46	F	25.8913
1424	54	M	26.3704

id	name	gender	age
454	stu53	F	18
404	stu3	F	19
477	stu76	F	19
447	stu46	F	20
460	stu59	F	20
442	stu41	F	20
478	stu77	F	21
472	stu71	F	21
484	stu83	F	21
469	stu68	F	21
463	stu62	F	21
494	stu93	F	21
451	stu50	F	22
444	stu43	F	22
406	stu5	F	23
452	stu51	F	23
464	stu63	F	23
471	stu70	F	24
466	stu65	F	24
417	stu16	F	25
415	stu14	F	25
480	stu79	F	25
488	stu87	F	25
433	stu32	F	25

备注1:由于测试脚本时多次失败,在删除表数据后再次运行脚本时,由于创建表时,设置ID字段是自动增长的,所以用户ID自动依次增加了;

备注2:“‘$stu_name'”,”F”,’$stu_age’,在引用shell变量到SQL语句中的时候需要用单引号,
另外,由于”mysql  -e”命令后面的SQL语句需要用单引号,所以字符串需改用双引号;

Leave a Reply

Your email address will not be published. Required fields are marked *