MySQL 游标的定义与使用方式

 更新时间:2021年1月22日 10:00  点击:1979

创建游标

首先在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;
    select _n,n,total;
  end;
  begin
  
  end;
  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 游标的定义与使用方式的详细内容,更多关于MySQL 游标的资料请关注猪先飞其它相关文章!

[!--infotagslink--]

相关文章

  • MySQL性能监控软件Nagios的安装及配置教程

    这篇文章主要介绍了MySQL性能监控软件Nagios的安装及配置教程,这里以CentOS操作系统为环境进行演示,需要的朋友可以参考下...2015-12-14
  • 详解Mysql中的JSON系列操作函数

    新版 Mysql 中加入了对 JSON Document 的支持,可以创建 JSON 类型的字段,并有一套函数支持对JSON的查询、修改等操作,下面就实际体验一下...2016-08-23
  • 深入研究mysql中的varchar和limit(容易被忽略的知识)

    为什么标题要起这个名字呢?commen sence指的是那些大家都应该知道的事情,但往往大家又会会略这些东西,或者对这些东西一知半解,今天我总结下自己在mysql中遇到的一些commen sense类型的问题。 ...2015-03-15
  • MySQL 字符串拆分操作(含分隔符的字符串截取)

    这篇文章主要介绍了MySQL 字符串拆分操作(含分隔符的字符串截取),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-22
  • mysql的3种分表方案

    一、先说一下为什么要分表:当一张的数据达到几百万时,你查询一次所花的时间会变多,如果有联合查询的话,有可能会死在那儿了。分表的目的就在于此,减小数据库的负担,缩短查询时间。根据个人经验,mysql执行一个sql的过程如下:1...2014-05-31
  • Windows服务器MySQL中文乱码的解决方法

    我们自己鼓捣mysql时,总免不了会遇到这个问题:插入中文字符出现乱码,虽然这是运维先给配好的环境,但是在自己机子上玩的时候咧,总得知道个一二吧,不然以后如何优雅的吹牛B。...2015-03-15
  • 用VirtualBox构建MySQL测试环境

    宿主机使用网线的时候,客户机在Bridged Adapter模式下,使用Atheros AR8131 PCI-E Gigabit Ethernet Controller上网没问题。 宿主机使用无线的时候,客户机在Bridged Adapter模式下,使用可选项里唯一一个WIFI选项,Microsoft Virtual Wifi Miniport Adapter也无法上网,故弃之。...2013-09-19
  • Centos5.5中安装Mysql5.5过程分享

    这几天在centos下装mysql,这里记录一下安装的过程,方便以后查阅Mysql5.5.37安装需要cmake,5.6版本开始都需要cmake来编译,5.5以后的版本应该也要装这个。安装cmake复制代码 代码如下: [root@local ~]# wget http://www.cm...2015-03-15
  • 忘记MYSQL密码的6种常用解决方法总结

    首先要声明一点,大部分情况下,修改MySQL密码是需要有mysql里的root权限的...2013-09-11
  • MySQL数据库备份还原方法

    MySQL命令行导出数据库: 1,进入MySQL目录下的bin文件夹:cd MySQL中到bin文件夹的目录 如我输入的命令行:cd C:/Program Files/MySQL/MySQL Server 4.1/bin (或者直接将windows的环境变量path中添加该目录) ...2013-09-26
  • Mysql命令大全(详细篇)

    一、连接Mysql格式: mysql -h主机地址 -u用户名 -p用户密码1、连接到本机上的MYSQL。首先打开DOS窗口,然后进入目录mysql/bin,再键入命令mysql -u root -p,回车后提示你输密码.注意用户名前可以有空格也可以没有空格,但是密...2015-11-08
  • node.js如何操作MySQL数据库

    这篇文章主要介绍了node.js如何操作MySQL数据库,帮助大家更好的进行web开发,感兴趣的朋友可以了解下...2020-10-29
  • Navicat for MySQL 11注册码\激活码汇总

    Navicat for MySQL注册码用来激活 Navicat for MySQL 软件,只要拥有 Navicat 注册码就能激活相应的 Navicat 产品。这篇文章主要介绍了Navicat for MySQL 11注册码\激活码汇总,需要的朋友可以参考下...2020-11-23
  • mysql IS NULL使用索引案例讲解

    这篇文章主要介绍了mysql IS NULL使用索引案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...2021-08-14
  • 基于PostgreSQL和mysql数据类型对比兼容

    这篇文章主要介绍了基于PostgreSQL和mysql数据类型对比兼容,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-12-25
  • RHEL6.5编译安装MySQL5.6.26教程

    一、准备编译环境,安装所需依赖包yum groupinstall 'Development' -y yum install openssl openssl-devel zlib zlib-devel -y yum install readline-devel pcre-devel ncurses-devel bison-devel cmake -y二、编译安...2015-10-21
  • Mysql中 show table status 获取表信息的方法

    这篇文章主要介绍了Mysql中 show table status 获取表信息的方法的相关资料,需要的朋友可以参考下...2016-03-12
  • 20分钟MySQL基础入门

    这篇文章主要为大家分享了20分钟MySQL基础入门教程,快速掌握MySQL基础知识,真正了解MySQL,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-12-02
  • mongodb与mysql命令详细对比

    传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关...2013-09-11
  • Delphi远程连接Mysql的实现方法

    这篇文章主要介绍了Delphi远程连接Mysql的实现方法,需要的朋友可以参考下...2020-06-30