在shell脚本中连接mysql并进行相关操作

在实际使用中,有时候需要定时的对数据库进行一些重复的操作。这样通过脚本的方式能更好的降低出错率并提高速度

连接数据库,我们可以封装一个函数来操作。方便进行数据的传递。将相关参数进度对应的传递。分析脚本我们可以知道就是将sql脚本以here文档的格式传递给mysql。

do_mysql(){
    mysql -h${host} -P${port} -u${account} -p${password} -D${database} -N -r -B << EOF
    ${1}
EOF
    }

那么我们就可以使用另一种直接传递文件的格式去传递sql语句

mysql -u ${account} -p${password} < table.sql

sql脚本的内容: use test; INSERT INTO media_session_20220831 (`session`, `meida_type`) VALUES(181026278212063, 'video');
对比会发现直接写在shell里的语句还是有区别的。在shell脚本中。符合’`'引起来的东西会被当做命令去解析。
也可以这样

echo "show databases;" | mysql -uroot -p123456

读取文件内容的方式,通过while循环实现

while read line
do 
   echo $line
   media_type=`echo $line|awk '{print $2}'`
done < media_session.txt
  • 每次读取文件的一行信息
  • 行信息中列信息的获取使用awk来实现

整体的使用方式

#!/bin/bash

#连接mysql
database=test
host=ip
port=3306
account=root
password=password
table_media=media_session_$(date +%Y%m%d)
table_data=statics_data_$(date +%Y%m%d)

#txt数据文件的路径及文件名
script=${1:-"media_session.txt"}

do_mysql(){
    mysql -h${host} -P${port} -u${account} -p${password} -D${database} -N -r -B << EOF
    ${1}
EOF
    }


#连接数据库并执行
create_tables(){
mysql -u ${account} -p${password} <<EOF 
use ${database};
CREATE TABLE ${table_media} (
session varchar(255) COLLATE utf8_bin DEFAULT NULL,
meida_type varchar(255) COLLATE utf8_bin DEFAULT NULL,
id bigint(12) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;;
show tables;
EOF
}

# 插入session和media的关系
insert_data(){
while read line
do 
   media_type=`echo $line|awk '{print $2}'`
   session=`echo $line|awk '{print $1}'` 
#   echo ${session}
#   echo ${media_type}
   do_mysql "INSERT INTO ${table_media} (session, meida_type) VALUES(${session}, '${media_type}');"
done < ${script}

}



# 生成数据
static_data(){
do_mysql "CREATE TABLE ${table_data}  as select 
a.session '会话id',
case b.dial_type when 1 then '外呼'
when 2 then '入呼' else '其他' end '呼叫类型',
b.ani '主叫',
b.dnis '被叫',
b.meeting_create_time '呼叫时间',
case a.meida_type when 'audio' then '音频' 
when 'video' then '视频' else '其他'  end '媒体类型'
 from test.${table_media} a left join vcc.t_meeting_detail b on a.session=b.session_id;"
}


create_tables
insert_data
static_data

你可能感兴趣的:(mysql,数据库,sql)