【MySQL】函数及存储过程

news/2024/9/28 20:13:41 标签: mysql, adb, android

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 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">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
)
begin
    declare 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 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)

返回值和返回集

  • 创建存储过程
mysql">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 ;
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 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)

  • 事务和异常

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

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

油标和存储过程

mysql">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.niftyadmin.cn/n/5681771.html

相关文章

速盾:cdn是怎么加速视频的?

CDN(Content Delivery Network)是一种网络加速服务,通过将内容分发到全球各地的服务器节点上,提供更快速度和更可靠的内容传输。当涉及到视频内容时,CDN起到了至关重要的作用,它通过一系列的技术和策略来加…

python程序操作Windows系统中的软件如word等(是否可以成功操作待验证)

一、python打开word软件 在 Python 中可以使用python-docx库来操作 Word 文档,但如果你的需求是直接打开 Word 软件,你可以使用os模块和subprocess模块来实现。以下是示例代码: import os import subprocessdef open_word():word_path rC:…

brew禁止更新

在运行 brew install maven 时,Homebrew 自动更新并显示了一些提示。以下是你可以选择的操作: 1. 继续安装 Maven 如果你不介意 Homebrew 自动更新并想继续安装 Maven,你可以直接等待更新完成,Maven 会自动安装。 2. 禁用 Home…

SpringBoot使用hutool操作FTP

项目场景&#xff1a; SpringBoot使用hutool操作FTP&#xff0c;可以实现从FTP服务器下载文件到本地&#xff0c;以及将本地文件上传到FTP服务器的功能。 实现步骤&#xff1a; 1、引入依赖 <dependency><groupId>commons-net</groupId><artifactId>…

干货 | 2024大模型十大趋势(免费下载)

导读&#xff1a;近日&#xff0c;在2024世界人工智能大会上&#xff0c;腾讯正式发布了《2024大模型十大趋势——走进“机器外脑”时代》报告。目前&#xff0c;这一报告正在AI产业界各大社群快速传播。报告中&#xff0c;腾讯研究院试图通过10个关键性的趋势&#xff0c;去理…

ScrapeGraphAl AI爬虫

官网&#xff1a;https://scrapegraph-ai.readthedocs.io/en/latest/ from flask import Flask, request, jsonify from scrapegraphai.graphs import SmartScraperGraphapp Flask(__name__)openai_key "sk-xxxxxxxxxxxxxxxxxxxx"graph_config {"llm":…

babylon.js-1:入门篇

最近项目中使用到了 Babylon.js 这门技术&#xff0c;从今天开始&#xff0c;抽取自己写的比较好的拿出来&#xff0c;作为分享案例&#xff1a; 记录学习成果通过笔记的方式记录技术积累方便工作中查找翻阅实现案例 是什么 Babylon.js是一个基于WebGL的开源3D渲染引擎&…

基于冲突动态监测算法的健身房预约管理系统

系统展示 用户前台界面 管理员后台界面 系统背景 随着健身热潮的兴起&#xff0c;健身房管理面临着日益增长的会员需求与资源分配的挑战。传统的人工预约方式不仅效率低下&#xff0c;且容易出现时间冲突和资源浪费的情况。为了解决这一问题&#xff0c;基于冲突动态监测算法的…