MySQL Cursor
MySQL Cursor
Summary: in this tutorial, you will learn how to use MySQL cursor in stored procedures to iterate through a result set returned by a SELECT statement.
Introduction to MySQL cursor
To handle a result set inside a stored procedure, you use a cursor. A cursor allows you to iteratea set of rows returned by a query and process each row accordingly.
MySQL cursor is read-only, non-scrollable and asensitive.
- Read only: you cannot update data in the underlying table through the cursor.
- Non-scrollable: you can only fetch rows in the order determined by the SELECT statement. You cannot fetch rows in the reversed order. In addition, you cannot skip rows or jump to a specific row in the result set.
- Asensitive: there are two kinds of cursors: asensitive cursor and insensitive cursor. An asensitive cursor points to the actual data, whereas an insensitive cursor uses a temporary copy of the data. An asensitive cursor performs faster than an insensitive cursor because it does not have to make a temporary copy of data. However, any change that made to the data from other connections will affect the data that is being used by an asensitive cursor, therefore, it is safer if you don’t update the data that is being used by an asensitive cursor. MySQL cursor is asensitive.
You can use MySQL cursors in stored procedures, stored functions, and triggers.
Working with MySQL cursor
First, you have to declare a cursor by using the DECLARE
statement:
1
|
DECLARE cursor_name CURSOR FOR SELECT_statement;
|
The cursor declaration must be after any variabledeclaration. If you declare a cursor before variables declaration, MySQL will issue an error. A cursor must always be associated with aSELECT
statement.
Next, you open the cursor by using the OPEN
statement. The OPEN
statement initializes the result set for the cursor, therefore, you must call the OPEN
statement before fetching rows from the result set.
1
|
OPEN cursor_name;
|
Then, you use the FETCH
statement to retrieve the next row pointed by the cursor and move the cursor to the next row in the result set.
1
|
FETCH cursor_name INTO variables list;
|
After that, you can check to see if there is any row available before fetching it.
Finally, you call the CLOSE
statement to deactivate the cursor and release the memory associated with it as follows:
1
|
CLOSE cursor_name;
|
When the cursor is no longer used, you should close it.
When working with MySQL cursor, you must also declare a NOT FOUND
handler to handle the situation when the cursor could not find any row. Because each time you call the FETCH
statement, the cursor attempts to read the next row in the result set. When the cursor reaches the end of the result set, it will not be able to get the data, and a condition is raised. The handler is used to handle this condition.
To declare a NOT FOUND
handler, you use the following syntax:
1
|
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
|
Where finished
is a variable to indicate that the cursor has reached the end of the result set. Notice that the handler declaration must appear after variable and cursor declaration inside the stored procedures.
The following diagram illustrates how MySQL cursor works.
MySQL Cursor Example
We are going to develop a stored procedure that builds an email list of all employees in theemployees
table in the MySQL sample database.
First, we declare some variables, a cursor for looping over the emails of employees, and a NOT FOUND
handler:
1
2
3
4
5
6
7
8
9
10
|
DECLARE finished INTEGER DEFAULT 0;
DECLARE email varchar(255) DEFAULT "";
-- declare cursor for employee email
DEClARE email_cursor CURSOR FOR
SELECT email FROM employees;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
|
Next, we open the email_cursor
by using the OPEN
statement:
1
|
OPEN email_cursor;
|
Then, we iterate the email list, and concatenate all emails where each email is separated by a semicolon(;):
1
2
3
4
5
6
7
8
|
get_email: LOOP
FETCH email_cursor INTO v_email;
IF v_finished = 1 THEN
LEAVE get_email;
END IF;
-- build email list
SET email_list = CONCAT(v_email,";",email_list);
END LOOP get_email;
|
After that, inside the loop we used the v_finished
variable to check if there is any email in the list to terminate the loop.
Finally, we close the cursor using the CLOSE
statement:
1
|
CLOSE email_cursor;
|
The build_email_list
stored procedure is as follows:
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
28
29
30
31
32
33
34
35
36
|
DELIMITER $$
CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_email varchar(100) DEFAULT "";
-- declare cursor for employee email
DEClARE email_cursor CURSOR FOR
SELECT email FROM employees;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN email_cursor;
get_email: LOOP
FETCH email_cursor INTO v_email;
IF v_finished = 1 THEN
LEAVE get_email;
END IF;
-- build email list
SET email_list = CONCAT(v_email,";",email_list);
END LOOP get_email;
CLOSE email_cursor;
END$$
DELIMITER ;
|
You can test the build_email_list
stored procedure using the following script:
1
2
3
|
SET @email_list = "";
CALL build_email_list(@email_list);
SELECT @email_list;
|
In this tutorial, we have shown you how to use MySQL cursor to iterate a result set and process each row accordingly.
MySQL Cursor的更多相关文章
- mysql cursor游标的使用,实例
mysql被oracle收购后,从mysql-5.5开始,将InnoDB作为默认存储引擎,是一次比较重大的突破.InnoDB作为支持事务的存储引擎,拥有相关的RDBMS特性:包括ACID事务支持,数据 ...
- MySQL Cursor Demo
-- 使用cursor的demo -- ==============================## -- 删除存储过程 DROP PROCEDURE USP_TestCursor; DELIMI ...
- cursor游标(mysql)
/* 游标 cursor 什么是游标?为什么需要游标 使用存储过程对sql进行编程的时候,我们查询的语句可能是数据是多个,它总是一口气全部执行,我们无法针对每一条进行判断.也就是说,我们无法控制程序的 ...
- Mysql游标的简明写法
-- cursor 游标/*declare 声明; declare 游标名 cursor for select_statement;open 找开; open 游标名fetch 取值; fetch 游 ...
- C API向MySQL插入批量数据的快速方法——关于mysql_autocommit
MySQL默认的数据提交操作模式是自动提交模式(autocommit).这就表示除非显式地开始一个事务,否则每个查询都被当做一个单独的事务自动执行.我们可以通过设置autocommit的值改变是否是自 ...
- python操作MongoDB、MySQL、Postgres、Sqlite、redis实例
总结:除了MongoDB.redis,其他三个数据库用python来操作其实是差不多的.所有例子都很简单,实际生产环境中的数据库操作远比这复杂得多,命令也比我例子中的多得多,我这里高级一点的用法就是批 ...
- MySQL数据库再回首
前言: 数据库是程序员的数据源泉,加上近期 要开发DB可视化.性能分析的功能 重新回顾一下MySQL知识,以下是笔记: MySQL架构 MySQL基础理论 1.什么是关系型数据库? 关系型数据库,这个 ...
- python mysql数据库操作
一.pymysql 模块安装(本文博客推荐:https://www.cnblogs.com/clschao/articles/10023248.html) pip3 install pymysql 二 ...
- 自定义 Mysql 类 与 自定义 异常类
import MySQLdb class MyExcept(Exception): ''' 常见做法定义异常基类,然后在派生不同类型的异常 ''' def __init__(self, *args): ...
随机推荐
- javascript之-深入事件机制
作者:yuyuyu链接:https://zhuanlan.zhihu.com/p/24620643来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 1.1 事件绑定的方式 ...
- [Java面试十一]数据库总结.
问题及描述: --1.学生表 Student(SID,Sname,Sage,Ssex) --SID 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别 --2.课程表 Course ...
- Nginx反向代理搭建配置
1.反向代理方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将服务器上得到的结果返回给internet 上请求连接的客户端,此时代理服务器对外就表现为一个 ...
- Android 实现应用升级方案(暨第三方自动升级服务无法使用后的解决方案)
第三方推送升级服务不再靠谱: 以前在做Android开发的时候,在应用升级方面都是使用的第三方推送升级服务,但是目前因为一些非技术性的问题,一些第三方厂商不再提供自动升级服务,比如友盟,那么当第三方推 ...
- Mybatis的缺陷
Mybatis是业界非常流行的持久层框架,轻量级.易用,在金融IT领域完全是领军地位,比Hibernate更受欢迎,优势非常多,也是非常值得我们学习的.但Mybatis并不尽善尽美,其自身的设计.编码 ...
- mysql基础知识扫盲
本篇主要介绍关于mysql的一些非常基础的知识,为后面的sql优化做准备. 一:连接mysql 关于mysql的下载和安装我在这里就不说了,第一步我们要连接我们的mysql服务器,打开cmd命令切换到 ...
- MySQL(一) 数据表数据库的基本操作
序言 这类文章,记录我看<MySQL5.6从零开始学>这本书的过程,将自己觉得重要的东西记录一下,并有可能帮助到你们,在写的博文前几篇度会非常基础,只要动手敲,跟着我写的例子全部实现一遍, ...
- Html与CSS快速入门02-HTML基础应用
这部分是html细节知识的学习. 快速入门系列--HTML-01简介 快速入门系列--HTML-02基础元素 快速入门系列--HTML-03高级元素和布局 快速入门系列--HTML-04进阶概念 示例 ...
- Script Task 引用 package variable
Script Task 能够使用C#代码进行编程,许多复杂的逻辑都可以使用C# 脚本来实现,不仅灵活,而且强大. 1,能够传递package variable 给 Script Task ,并且Scr ...
- SharePoint Server 2013开发之旅(二):使用在线的开发人员网站进行SharePoint App开发
上一篇我已经介绍了新版本的SharePoint Server提供了四种主要的开发场景,其中一个全新的App开发模型让我们眼前一亮.这一篇我将介绍如何在线进行SharePoint App开发. 谈到Sh ...