mysql游标的原理与用法实例分析

吾爱主题 阅读:206 2024-04-05 16:20:58 评论:0

本文实例讲述了mysql游标的原理与用法。分享给大家供大家参考,具体如下:

本文内容:

  • 什么是游标
  • 创建游标
  • 使用游标

首发日期:2018-04-18

 


 

什么是游标:

  • 如果你前面看过mysql函数,会发现无法使用返回多行结果的语句。但如果你又确实想要使用时,就需要使用到游标,游标可以帮你选择出某个结果(这样就可以做到返回单个结果)。
  • 另外,使用游标也可以轻易的取出在检索出来的行中前进或后退一行或多行的结果。
  • 游标可以遍历返回的多行结果。

补充:

  • Mysql中游标只适用于存储过程以及函数。

 


 

创建游标:

  • 语法:
    • 1.定义游标:declare 游标名 cursor for select语句;
    • 2.打开游标:open 游标名;
    • 获取结果:fetch 游标名 into 变量名[,变量名];
    • 关闭游标:close 游标名; ?
      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 create procedure p1() begin    declare id int ;    declare name varchar( 15 );    - - 声明游标    declare mc cursor for select * from class ;    - - 打开游标    open mc;    - - 获取结果    fetch mc into id ,name;    - - 这里是为了显示获取结果    select id ,name;    - - 关闭游标    close mc;    end;
    ?
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 create procedure p2() begin    declare id int ;    declare name varchar (15);    -- 声明游标    declare mc cursor for select * from class;    -- 打开游标    open mc;    -- 获取结果    loop -- 循环,将表的内容都转移到class2中    fetch mc into id, name ;    -- 这里是为了显示获取结果    insert into class2 values (id, name );    -- 关闭游标    end loop;    close mc;    end ;

 


 

使用游标:

  • 游标每一次fetch都是获取一行结果,可以使用变量来获取fetch到的每一列的值
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 create procedure p2() begin    declare id int ;    declare name varchar (15);    -- 声明游标    declare mc cursor for select * from class;    -- 打开游标    open mc;    -- 获取结果    loop -- 循环,将表的内容都转移到class2中    fetch mc into id, name ;    -- 这里是为了显示获取结果    insert into class2 values (id, name );    -- 关闭游标    end loop;    close mc;    end ;

上面的代码会有一个报错,不断循环的话,始终会达到表的末尾,到了末尾就无法继续fetch,一般来说都要避免报错,到了末尾前会有一个mysql定义的

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 create procedure p3() begin    declare id int ;    declare name varchar (15);    declare flag int default 0;    -- 声明游标    declare mc cursor for select * from class;    declare continue handler for not found set flag = 1;    -- 打开游标    open mc;    -- 获取结果    l2:loop       fetch mc into id, name ;    if flag=1 then -- 当无法fetch会触发handler continue      leave l2;    end if;    -- 这里是为了显示获取结果    insert into class2 values (id, name );    -- 关闭游标    end loop;    close mc;    end ;   call p3(); -- 不报错 select * from class2;

希望本文所述对大家MySQL数据库计有所帮助。

原文链接:https://www.cnblogs.com/progor/p/8875100.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容