MySql中游标的定义与使用方式

本文介绍如何在MySQL中使用存储过程和游标来统计特定产品的库存总量,并提供了三种不同的循环实现方法。
首先在MySql中创建一张数据表:
CREATE TABLE IF NOT EXISTS `store` 
        ( `id` int(11) NOT NULL AUTO_INCREMENT, 
         `name` varchar(20) NOT NULL, 
         `count` int(11) NOT NULL DEFAULT '1', 
         PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7; 


INSERT INTO `store` (`id`, `name`, `count`) 
VALUES (1, 'android', 15), (2, 'iphone', 14), (3, 'iphone', 20), (4, 'android', 5), (5, 'android', 13), (6, 'iphone', 13);


我们现在要用存储过程做一个功能,统计iphone的总库存是多少,并把总数输出到控制台。


--在windows系统中写存储过程时,如果需要使用declare声明变量,需要添加这个关键字,否则会报错。 
delimiter // 
drop procedure if exists StatisticStore; 
CREATE PROCEDURE StatisticStore() 
        BEGIN 
                --创建接收游标数据的变量 
                declare c int; 
                declare n varchar(20);
                 --创建总数变量 
                declare total int default 0; 
                --创建结束标志变量 
                declare done int default false; 
                --创建游标 
                declare cur cursor for select name,count from store where name = 'iphone'; 
                --指定游标循环结束时的返回值 
                declare continue HANDLER for not found set done = true; 
                --设置初始值 
                set total = 0; 
                --打开游标 
                open cur;
                 --开始循环游标里的数据 
                read_loop:loop
                 --根据游标当前指向的一条数据 
                fetch cur into n,c;
                 --判断游标的循环是否结束 
                if done then leave read_loop;
                --跳出游标循环 
                end if; 
                --获取一条数据时,将count值进行累加操作,这里可以做任意你想做的操作, 
                set total = total + c; 
                --结束游标循环
                 end loop; 
                --关闭游标 
                close cur; 
                 --输出结果 
                select total; 
        END; 
--调用存储过程 call StatisticStore();


fetch是获取游标当前指向的数据行,并将指针指向下一行,当游标已经指向最后一行时继续执行会造成游标溢出。 使用loop循环游标时,他本身是不会监控是否到最后一条数据了,像下面代码这种写法,就会造成死循环;
read_loop:loop 
        fetch cur into n,c; 
        set total = total+c; 
end loop;
在MySql中,造成游标溢出时会引发mysql预定义的NOT FOUND错误,所以在上面使用下面的代码指定了当引发not found错误时定义一个continue 的事件,指定这个事件发生时修改done变量的值。
declare continue HANDLER for not found set done = true;
所以在循环时加上了下面这句代码:
--判断游标的循环是否结束 
        if done then leave read_loop;
--跳出游标循环 
        end if;
如果done的值是true,就结束循环。继续执行下面的代码。
使用方式
游标有三种使用方式: 第一种就是上面的实现,使用loop循环; 第二种方式如下,使用while循环:
drop procedure if exists StatisticStore1; 
CREATE PROCEDURE StatisticStore1() 
        BEGIN declare c int; 
                declare n varchar(20); 
                declare total int default 0; 
                declare done int default false; 
                 
                 declare cur cursor for select name,count from store where name = 'iphone';
                 declare continue HANDLER for not found set done = true; 
                set total = 0; 
                open cur; fetch cur into n,c;
                 while(not done) do 
                        set total = total + c; 
                        fetch cur into n,c; 
                end while; 
                close cur; 
                select total; 
        END; 
call StatisticStore1();
第三种方式是使用repeat执行:
drop procedure if exists StatisticStore2; 
CREATE PROCEDURE StatisticStore2() 
        BEGIN
                 declare c int; 
                 declare n varchar(20); 
                 declare total int default 0; 
                declare done int default false; 
                
                declare cur cursor for select name,count from store where name = 'iphone'; 
                declare continue HANDLER for not found set done = true; 
                set total = 0; 
                open cur; 
                repeat 
                        fetch cur into n,c; 
                        if not done then 
                                set total = total + c; 
                        end if; 
                until done end repeat; 
                close cur; 
                select total; 
                 END; 
call StatisticStore2();
游标嵌套
在mysql中,每个begin end 块都是一个独立的scope区域,由于MySql中同一个error的事件只能定义一次,如果多定义的话在编译时会提示Duplicate handler declared in the same block。
drop procedure if exists StatisticStore3;
CREATE PROCEDURE StatisticStore3() 
        BEGIN declare _n varchar(20); 
                declare done int default false; 
                declare cur cursor for select name from store group by name; 
                declare continue HANDLER for not found set done = true; 
                open cur; 
                read_loop:loop 
                        fetch cur into _n; 
                        if done then 
                                leave read_loop; 
                        end if; 
                begin 
                        declare c int; 
                        declare n varchar(20); 
                        declare total int default 0; 
                        declare done int default false; 
                        declare cur cursor for select name,count from store where name = 'iphone'; 
                        declare continue HANDLER for not found set done = true; 
                        set total = 0; 
                        open cur; 
                          iphone_loop:loop 
                                fetch cur into n,c; 
                                if done then 
                                        leave iphone_loop; 
                                end if; 
                                set total = total + c; 
                        end loop; 
                        close cur; 
                        select _n,n,total; 
                end; 
                begin 
                        declare c int; 
                        declare n varchar(20); 
                        declare total int default 0; 
                        declare done int default false; 
                        declare cur cursor for select name,count from store where name = 'android'; 
                        declare continue HANDLER for not found set done = true; 
                        set total = 0; 
                        open cur; 
                        android_loop:loop 
                                fetch cur into n,c; 
                                if done then 
                                        leave android_loop; 
                                end if; 
                        set total = total + c; 
                          end loop; 
                        close cur; 
              END; 
call StatisticStore3(); 
上面就是实现一个嵌套循环,当然这个例子比较牵强。凑合看看就行。。
动态SQL
Mysql 支持动态SQL的功能, 
set @sqlStr='select * from table where condition1 = ?'; 
prepare s1 for @sqlStr; 
--如果有多个参数用逗号分隔 
execute s1 using @condition1; 
--手工释放,或者是 connection 关闭时, server 自动回收 
deallocate prepare s1;
阅读更多
个人分类: MySql


来源网址:https://blog.youkuaiyun.com/liguo9860/article/details/50848216
### 数据库游标定义使用 #### 1. 游标的概念定义 游标(Cursor)是数据库系统中的一种机制,用于逐行访问和操作查询结果集中的数据。它提供了一种从面向集合的数据库系统中抽离出单行数据的能力[^1]。通过游标,可以对从数据库中 `SELECT` 查询得到的每一行进行独立的操作,从而满足对特定行进行特殊处理的需求。 游标通常被描述为一种指向结果集中某一行的指针[^3]。当需要对查询结果中的每一条记录逐一处理时,游标提供了便利的手段。例如,在一个电话本中查找特定联系人时,游标的作用类似于手逐条扫描电话本上的记录,直到找到目标记录为止[^3]。 #### 2. 游标的特性 游标具有以下几种主要特性: - **静态性(STATIC)**:在这种模式下,游标的结果集在打开时即已固定,后续对基础表的任何更改都不会反映在游标的结果集中[^2]。此外,对游标数据所做的更改也不会保存到基础数据库表中。 - **键集驱动(KEYSET)**:键集游标基于结果集中行的唯一标识符(键)来操作数据。这种类型的游标可以看到对最初存在于游标中的行所做的更改,但无法看到新添加到表中的行[^2]。 - **动态性(DYNAMIC)**:动态游标能够实时反映基础表中的所有更改,包括插入、更新和删除操作。同时,对游标内数据的更改也会直接作用于基础数据库表[^2]。 #### 3. 游标使用场景 游标的主要用途是在需要逐行处理查询结果的情况下提供支持。以下是几个常见的使用场景: - **复杂业务逻辑**:当需要对查询结果中的每一行应用复杂的业务逻辑时,游标可以确保每行数据都能被独立处理[^1]。 - **分页查询**:在实现分页功能时,游标可以帮助定位到特定的结果行,并从中提取所需的数据。 - **数据敏感性处理**:对于需要实时反映基础表变化的场景,动态游标是一种有效的解决方案。 #### 4. 游标的语法示例 以下是一个在 MySQL使用游标的简单示例,展示如何遍历查询结果并进行逐行处理: ```sql DELIMITER $$ CREATE PROCEDURE process_rows() BEGIN DECLARE done INT DEFAULT FALSE; DECLARE row_id INT; DECLARE cur CURSOR FOR SELECT id FROM example_table; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur; read_loop: LOOP FETCH cur INTO row_id; IF done THEN LEAVE read_loop; END IF; -- 对每一行执行具体操作 UPDATE example_table SET status = 'processed' WHERE id = row_id; END LOOP; CLOSE cur; END$$ DELIMITER ; ``` 上述代码定义了一个存储过程,通过游标逐行读取 `example_table` 表中的 `id` 值,并对每行执行更新操作。 #### 5. 游标的优缺点 - **优点**: - 提供了逐行操作数据的能力,适合处理复杂的业务逻辑[^1]。 - 支持多种数据敏感性需求,如静态、键集驱动和动态游标[^2]。 - **缺点**: - 性能开销较大,特别是在处理大规模数据集时[^1]。 - 使用不当可能导致资源占用过多或程序效率低下。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值