当前位置: 首页 > article >正文

MySQL函数及存储过程

MySQL函数和存储过程

函数

数据库中的函数是一种可重复使用的命名代码块,用于在数据库中执行特定的操作或计算。
在MySQL中提供了很多函数,为我们的SQL提供了便利

  • 内置函数
mysql> select count(r_id),max(r_id),min(r_id),avg(r_id) from resume_library;
+-------------+-----------+-----------+------------+
| count(r_id) | max(r_id) | min(r_id) | avg(r_id)  |
+-------------+-----------+-----------+------------+
|       26764 |     27195 |         1 | 13491.3612 |
+-------------+-----------+-----------+------------+
1 row in set (0.03 sec)

mysql> select r_id,reverse(姓名) from resume_library where 姓名 like '于金_';
+-------+---------------+
| r_id  | reverse(姓名) |
+-------+---------------+
|   285 | 曼金于        |
| 20499 | 淼金于        |
|   286 | 龙金于        |
+-------+---------------+
3 rows in set (0.00 sec)

mysql> select r_id,concat('阿龙','真帅'),now(),date_format(now(),'%Y-%m-%d %H:%i:%s') from resume_library where r_id=1;

+------+-----------------------+---------------------+----------------------------------------+
| r_id | concat('阿龙','真帅') | now()               | date_format(now(),'%Y-%m-%d %H:%i:%s') |
+------+-----------------------+---------------------+----------------------------------------+
|    1 | 阿龙真帅              | 2024-09-22 17:30:22 | 2024-09-22 17:30:22                    |
+------+-----------------------+---------------------+----------------------------------------+
1 row in set (0.00 sec)

-- 字符拼接
mysql> select concat('阿龙','真帅');
+-----------------------+
| concat('阿龙','真帅') |
+-----------------------+
| 阿龙真帅              |
+-----------------------+
1 row in set (0.00 sec)

-- 睡眠5秒
mysql> select sleep(5);
+----------+
| sleep(5) |
+----------+
|        0 |
+----------+
1 row in set (5.00 sec)
  • 创建函数
-- 更改结束标志符号,方便创建函数
mysql> delimiter $$
mysql> create function f1()
    ->     returns int
    -> begin
    ->     declare num int;
    ->     declare minid int;
    ->     declare maxid int;
    ->     select max(r_id) from resume.resume_library into maxid;
    ->     select min(r_id) from resume.resume_library into minid;
    ->     set num = maxid + minid;
    ->     return (num);
    -> end $$
Query OK, 0 rows affected (0.00 sec)
-- 更改结束标志符号
mysql> delimiter ;
  • 执行函数
select f1() from resume.resume_library;
  • 删除函数
mysql> drop function f1;
Query OK, 0 rows affected (0.00 sec)

存储过程

存储过程,是一个存储MySQL中上sql语句的集合,当主动去调用存储过程时,其中内部的sql语句按照逻辑执行。

  • 创建存储过程
mysql> create procedure p1()
    -> begin
    -> select * from t3;
    -> end $$
Query OK, 0 rows affected (0.00 sec)
  • 执行存储过程
call p1();
  • Python程序执行存储过程
# -*- coding: UTF-8 -*-
"""
@Project :lufei-learning-city 
@File    :存储过程.py
@IDE     :PyCharm 
@Author  :于金龙@阿龙的代码在报错
@Date    :2024/9/22 下午6:29 
"""
import pymysql

conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='20020115',
    db='resume',
    charset='utf8'
)
cursor = conn.cursor()

cursor.callproc('p1')
result = cursor.fetchall()
cursor.close()
conn.close()
print(result)
  • 删除存储过程
mysql> drop procedure p1;
Query OK, 0 rows affected (0.00 sec)

参数类型

存储过程的参数可以分为三种类型:

  • in,仅用于传入参数
  • out,仅用于返回参数
  • inout,既可以传入又可以当做返回值
use user;
-- 更改结束标识符
delimiter $$
create procedure p2(
    in i1 int,
    in i2 int,
    inout i3 int,
    out r1 int
)
begin
    declare temp1 int;
    declare temp2 int default 0;
    set temp1 = 1;
    set r1 = i1 + i2 + temp1 + temp2;
    set i3 = i3 + 100;
end $$

-- 更改结束标识符
delimiter ;

调用存储过程

set @t1=4;
set @t2=0;
call p2(1,2,@t1,@t2)
select @t1,@t2

python进行执行

# -*- coding: UTF-8 -*-
"""
@Project :lufei-learning-city 
@File    :存储过程.py
@IDE     :PyCharm 
@Author  :于金龙@阿龙的代码在报错
@Date    :2024/9/22 下午6:29 
"""
import pymysql

conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='20020115',
    db='user',
    charset='utf8'
)
cursor = conn.cursor()

# cursor.callproc('p1')
# result = cursor.fetchall()

cursor.callproc('p2', args=(1, 22, 3, 4))
table = cursor.fetchall()

cursor.execute('select @_p2_0,@_p2_1,@_p2_2,@_p2_3')
result = cursor.fetchall()

cursor.close()
conn.close()
print(result)

返回值和返回集

  • 创建存储过程
delimiter $$

create procedure p3(
    in n1 int,
    inout n2 int,
    out n3 int
)
begin
    set n2 = n1 + 100;
    set n3 = n2 + n1 + 100;
    select * from girl;
end $$
delimiter ;
set @t1 = 4;
set @t2 = 0;
call p3(1, @t1, @t2);
select @t1, @t2;
# -*- coding: UTF-8 -*-
"""
@Project :lufei-learning-city 
@File    :存储过程.py
@IDE     :PyCharm 
@Author  :于金龙@阿龙的代码在报错
@Date    :2024/9/22 下午6:29 
"""
import pymysql

conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='20020115',
    db='user',
    charset='utf8'
)

cursor = conn.cursor()
cursor.callproc('p3', args=(22, 3, 4))
table = cursor.fetchall()  # 执行过程中的结果集
# 获取执行完存储参数
cursor.execute('select @_p3_0,@_p3_1,@_p3_2')
result = cursor.fetchall()

cursor.close()
conn.close()
print(result)
print(table)

  • 事务和异常

事务,成功都成功,失败都失败

delimiter $$
create procedure p4(
    out p_return_code tinyint
)
begin
    declare exit handler for sqlexception
        begin
            -- error
            set p_return_code = 1;
            rollback;
        end;
    declare exit handler for sqlwarning
        begin
            -- waring
            set p_return_code = 2;
            rollback;
        end;
    start transaction ; -- 开启事务
    delete from girl;
    insert into girl(name) values ('1');
    commit; -- 提交事务
    set p_return_code = 0;
end $$
delimiter ;

python进行执行

# -*- coding: UTF-8 -*-
"""
@Project :lufei-learning-city 
@File    :存储过程.py
@IDE     :PyCharm 
@Author  :于金龙@阿龙的代码在报错
@Date    :2024/9/22 下午6:29 
"""
import pymysql

conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='20020115',
    db='user',
    charset='utf8'
)
cursor = conn.cursor()

cursor.callproc('p4', args=(100,))
cursor.execute("select @_p4_0")
result = cursor.fetchall()
cursor.close()
conn.close()
print(result)

油标和存储过程

delimiter $$

create procedure p5()
begin
    declare sid int;
    declare sname varchar(50);
    declare done int default false;
    -- 声明油标
    declare my_cursor cursor for select id, name
                                 from girl;
    declare continue handler for NOT FOUND set done = TRUE;

    OPEN my_cursor;
    xxoo:loop
        fetch my_cursor into sid,sname;
        if done then
            leave xxoo;
        end if;
        insert into t1(name) values (sname);
    end loop xxoo;
    close my_cursor;
end $$
delimiter ;

call p5();

http://www.kler.cn/news/317848.html

相关文章:

  • 视频制作软件哪个好?前十名推荐!
  • 云手机的便捷性和安全性体现在哪?
  • redisson 延迟队列实现任务过期监听
  • Hbase操作手册
  • git笔记之重置本地仓库所有分支和远程保持一致、工作区恢复干净,像刚clone下来一样
  • 阅读记录:Gradient Episodic Memory for Continual Learning
  • 十三 系统架构设计(考点篇)
  • 【python】数据类型
  • react hooks--useCallback
  • 误删系统引导如何恢复?如何创建系统引导?
  • Vue 内存泄漏分析:如何避免开发过程中导致的内存泄漏问题
  • Appium高级话题:混合应用与原生应用测试策略
  • Mysql 常用方法和函数(查询)
  • 数据结构应试-树和二叉树
  • 这个浏览器插件:提高测试效率且好用!
  • Haskell网络编程:代理服务器的高级使用技巧
  • mac安装JetBtains全家桶新版本时报错:Cannot start the IDE
  • GitLab将会持续支持FluxCD
  • Vulkan 学习(9)---- vkSuraceKHR 创建
  • Matlab simulink建模与仿真 第十七章(补充离散库和补充数学库)
  • DevOps在提升软件质量方面的作用
  • 动手学深度学习8.5. 循环神经网络的从零开始实现-笔记练习(PyTorch)
  • Linux——常用系统设置和快捷键操作指令
  • 排序 (哈希) js
  • 视频无损压缩工具+预览视频生成工具
  • 文件上传js代码
  • git pull 报错 refusing to merge unrelated histories
  • 内容安全策略csp中的font-src如果设置为* ,会不安全吗
  • 滚雪球学SpringCloud[5.1讲]: Spring Cloud Config详解
  • Vue学习记录之六(组件实战及BEM框架了解)