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 proceduresstored 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 FETCHstatement, 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.

时间: 2024-10-07 03:07:48

MySQL Cursor的相关文章

mysql cursor 游标

以下说明基于mysql 5.5. 概述:我知道大部分人对于mysql游标使用的不多.mysql大多数情况可以用“集合”操作,即可满足90%的需求.mysql cursor作为对“记录”操作,是操作数据的一种补充. mysql cursor三大特性(大三“坑”): 1.只读的:cursor本身不提供修改数据的操作,只能fetch columns into variables.(当然你可以把数据拿出来以后,再用update语句操作一下,但是有坑,第三点说明). 2.不能滚动的:只能向一个方向遍历数据

cursor游标(mysql)

/* 游标 cursor 什么是游标?为什么需要游标 使用存储过程对sql进行编程的时候,我们查询的语句可能是数据是多个,它总是一口气全部执行,我们无法针对每一条进行判断.也就是说,我们无法控制程序的运行,所以引入了游标cursor cursor类似于java中的迭代器. 它利用查询语句生成一个游标,然后游标中有一个类似指针的东西.首先指在游标首,就是迭代器.不解释了 cursor 游标 declare声明: declare 游标名 cursor for select_statement; op

Windows7下Python3安装mysql连接器

Connector/python安装:     命令窗口(cmd)使用命令如下:easy_install pymysql3     在python3之后,MySQLdb被pymysql取代了.根据使用版本的不同,安装不同的连接器.     注意:这个需要在安装好python3.4之后使用. 测试     test.py程序编写如下: import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', pa

[Python]将Excel文件中的数据导入MySQL

Github Link 需求 现有2000+文件夹,每个文件夹下有若干excel文件,现在要将这些excel文件中的数据导入mysql. 每个excel文件的第一行是无效数据. 除了excel文件中已有的数据,还要添加一列,名为“at_company”,值为821. 流程 (1)获取excel文件列表,并根据excel文件名确定之后需要创建的table名: (2)连接mysql (3)创建table (4)插入数据 (5)断开连接 依赖模块 1. xlrd # to read excel fil

C API向MySQL插入批量数据的快速方法——关于mysql_autocommit

MySQL默认的数据提交操作模式是自动提交模式(autocommit).这就表示除非显式地开始一个事务,否则每个查询都被当做一个单独的事务自动执行.我们可以通过设置autocommit的值改变是否是自动提交autocommit模式.查询当前数据库事务提交方式的命令为: mysql> show variables like 'autocommit'; +---------------+-------+ | Variable_name | Value | +---------------+-----

数据库之Python操作MySQL

一.引言 Python操作MySQL一共有两种方式,第一种是用原生模块pymysql和mysqldb,这两种模块在py2中都支持,但是在py3中只支持pymysql,但是pymysql可以通过pymysql.install_as_MySQLdb()的方式构造成和mysqldb一样的使用:第二种方式是ORM框架 SQLAchemy. 二.pymysql 下载安装 pip install pymysql 增.删.改 import pymysql # 增,删,改除了sql语句不同,使用的方式一致 co

使用Python对MySQL数据库插入二十万条数据

1.当我们测试的时候需要大量的数据的时候,往往需要我们自己造数据,一条一条的加是不现实的,这时候就需要使用脚本来批量生成数据了. import pymysql import random import string # 建立数据库连接 mysql = pymysql.connect(host="数据库IP", user="数据库用户名",port=3306,password="数据库密码", charset='utf8', autocommit=

saltstack(七)返回值

一.自定义创建模块 在base目录下创建_modules目录,你自己编写的模块都可以存放在该目录下,当前目录结构下: 1 2 3 4 5 6 7 8 [[email protected]:]# tree -L 3 salt salt ├── etc ├── _grains │   ├── dmp_scribe.py │   └── zabbix_conf.py ├── _modules │   └── ip.py 通过上图可以看到已经创建了一个名为ip.py文件,看看相关内容: 1 2 3 4

memcached&redis性能测试

转自:http://www.iigrowing.cn/memcached-redis-xing-neng-ce-shi.html 一.Memcached 1.1.memcached简介 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提供动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通