MySQL在SQL中调用系统命令

MySQL在SQL语句中调用系统命令

一、前言

  • 环境
  1. LInux 发行版:CentOS Linux release 7.6.1810 (Core)
  2. MySQL:5.6.43
  • UDF

UDF(user-defined function) 是 MySQL 的一个拓展接口

  • 参考:

二、正文

1.工具安装

git安装

  • 查看版本,可用于检查当前系统是否安装 git
# git --version
  • 安装 git
# yum install git
  • 卸载 git
# yum remove git

gcc安装

# yum install gcc gcc-c++

mysql依赖包

已安装的可以跳过,或者 后面执行命令时,报错了再安装

  • 查看当前 mysql 版本
mysql> select version() from dual;
+-----------+
| version() |
+-----------+
| 5.6.43    |
+-----------+
1 row in set (0.00 sec)
  • 安装对应版本的依赖包

  • mysql-community-devel(依赖:mysql-community-common、mysql-community-libs)

# wget ./ [依赖包下载地址]
# rpm -ivh [需要安装的依赖包]

2.lib_mysqludf_sys安装

  • 查看 MySQL 的插件路径

/usr/lib64/mysql/plugin/

mysql> show variables like 'plugin_dir';
+---------------+--------------------------+
| Variable_name | Value                    |
+---------------+--------------------------+
| plugin_dir    | /usr/lib64/mysql/plugin/ |
+---------------+--------------------------+
1 row in set (0.00 sec)
  • 下载、编译和安装
# mkdir /opt/temp
# cd /opt/temp/
#-- git 克隆
# git clone https://github.com/mysqludf/lib_mysqludf_sys.git
# cd lib_mysqludf_sys
#-- 编译
# gcc -DMYSQL_DYNAMIC_PLUGIN -fPIC -Wall -I/usr/include/mysql -I. -shared lib_mysqludf_sys.c -o lib_mysqludf_sys.so
#-- 拷贝文件
# cp lib_mysqludf_sys.so /usr/lib64/mysql/plugin/
  • 连接 MySQL ,执行 lib_mysqludf_sys.sql
mysql> source /opt/temp/lib_mysqludf_sys/lib_mysqludf_sys.sql

Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

3.测试

  • 创建触发器
CREATE TRIGGER test_trigger AFTER insert
ON test_table FOR EACH ROW
BEGIN
	SELECT @id:=id,@name:=name FROM test_table INTO @temp;
	SET @command := 'mkdir /opt/'+@name+'_'+@id;
	SELECT sys_exec(@command) INTO @msg;
END
  • 最后,表中新增数据,测试触发器效果

三、其它

1.触发器创建报错

  • 报错:Not allowed to return a result set from a trigger

  • 原因:MySQL 5 之后的版本,不支持触发器返回结果集

  • 解决:在 SELECT 语句后加 INTO @msg,将结果先保存到 @msg 变量中,具体请参考的测试例子

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

趴着喝可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值