【MySQL】函数及存储过程

ops/2024/10/18 14:17:01/

MySQL函数和存储过程

函数

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

  • 内置函数
mysql">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">-- 更改结束标志符号,方便创建函数
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 ;
  • 执行函数
mysql">select f1() from resume.resume_library;
  • 删除函数
mysql">mysql> drop function f1;
Query OK, 0 rows affected (0.00 sec)

存储过程

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

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

参数类型

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

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

调用存储过程

mysql">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 pymysqlconn = 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)

返回值和返回集

  • 创建存储过程
mysql">delimiter $$create procedure p3(in n1 int,inout n2 int,out n3 int
)
beginset n2 = n1 + 100;set n3 = n2 + n1 + 100;select * from girl;
end $$
delimiter ;
mysql">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 pymysqlconn = 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)
  • 事务和异常

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

mysql">delimiter $$
create procedure p4(out p_return_code tinyint
)
begindeclare exit handler for sqlexceptionbegin-- errorset p_return_code = 1;rollback;end;declare exit handler for sqlwarningbegin-- waringset 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 pymysqlconn = 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)

油标和存储过程

mysql">delimiter $$create procedure p5()
begindeclare sid int;declare sname varchar(50);declare done int default false;-- 声明油标declare my_cursor cursor for select id, namefrom girl;declare continue handler for NOT FOUND set done = TRUE;OPEN my_cursor;xxoo:loopfetch my_cursor into sid,sname;if done thenleave xxoo;end if;insert into t1(name) values (sname);end loop xxoo;close my_cursor;
end $$
delimiter ;call p5();

http://www.ppmy.cn/ops/118208.html

相关文章

【优选算法之位运算】No.7--- 经典位运算算法

文章目录 前言一、位运算几种模型&#xff1a;1.1 基础的位运算&#xff1a; << >> ~ & | ^1.2 几种模型&#xff1a;1.3 模型练习 二、位运算示例&#xff1a;2.1 判定字符是否唯⼀2.2 丢失的数字2.3 两整数之和2.4 只出现⼀次的数字 II2.5 消失的两个数字 前…

Naive UI 选择器 Select 的:render-label 怎么使用(Vue3 + TS)

项目场景&#xff1a; 在Naive UI 的 选择器 Select组件中 &#xff0c;如何实现下面的效果 &#xff0c;在下拉列表中&#xff0c;左边展示色块&#xff0c;右边展示文字。 Naive UI 的官网中提到过这个实现方法&#xff0c;有一个render-label的api&#xff0c;即&#xff…

【ARM】MDK-当选择AC5时每次点击build都会全编译

【更多软件使用问题请点击亿道电子官方网站】 1、 文档目标 解决MDK中选择AC5时每次点击build都会全编译 2、 问题场景 在MDK中点击build时&#xff0c;正常会只进行增量编译&#xff0c;但目前每次点击的时候都会全编译。 3、软硬件环境 1 软件版本&#xff1a;Keil MDK 5.…

帆软通过JavaScript注入sql,实现数据动态查询

将sql语句设置为参数 新建数据库查询 设置数据库查询的sql语句 添加控件 JavaScript实现sql注入 添加事件 编写JavaScript代码 //获取评价人id var pjrid this.options.form.getWidgetByName("id").getValue();//显示评价人id alert("评价人&#xff1a;&…

【Linux】驱动的基本架构和编译

驱动源码 /** Silicon Integrated Co., Ltd haptic sih688x haptic driver file** Copyright (c) 2021 kugua <daokuan.zhusi-in.com>** This program is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public Licen…

【C语言】const char*强制类型转换 (type cast)的告警问题

void run_upload(const char *ftp_url) {CircularQueue queue;// 初始化环形队列for (int i = 0; i < QUEUE_SIZE; i++) {queue.items[i].data = malloc(BUFFER_SIZE);if (queue.items[i].data == NULL) {fprintf(stderr, "Failed to allocate memory for queue item %…

ML 系列:机器学习和深度学习的深层次总结(06)— 提升数据质量

一、说明 在AI数据挖掘中&#xff0c;对原始数据的预处理是必须的技术手段&#xff0c;本篇将对数据预处理的一系列注意事项进行展示。 二、关于数据预处理 注意&#xff1a; 在本章中&#xff0c;讨论的技术和方法基于 Roy Jafari 的《Hands-On Data Preprocessing in Pyth…

Linux下安装MATLAB R2017b教程

注意&#xff1a;以下命令均在 root 用户下进行&#xff0c;否则命令前需要加 sudo 1. 拷贝安装文件包 将解压后的 matlab 文件夹拷贝到 /usr/local 路径下&#xff0c;进入 .iso 文件目录下 cd /usr/local/MATLAB_R2017b_Linux/R2017b_glnxa64 2. 挂载 mount -o loop R…