search
HomeDatabaseMysql TutorialWhat is the use of mysql cursor?

In mysql, cursors function as pointers and are mainly used to traverse the record result set returned by querying the database in order to perform corresponding operations. A cursor is actually a mechanism that extracts one record at a time from a result set that contains multiple data records. The relational database management system is essentially set-oriented. In MySQL, there is no expression form to describe a single record in the table, unless the WHERE clause is used to limit only one record to be selected; so sometimes a cursor must be used to select a single record. data processing.

What is the use of mysql cursor?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

MySQL Cursor (Cursor)

A cursor is actually a method that can extract one record at a time from a result set that includes multiple data records. Mechanisms.

The cursor acts as a pointer.

Although the cursor can traverse all rows in the result, it only points to one row at a time.

The function of the cursor is to traverse the records returned by the query database in order to perform corresponding operations.

The relational database management system is essentially set-oriented. In MySQL, there is no expression form to describe a single record in the table, unless the WHERE clause is used to limit only one record to be selected. So sometimes we must use cursors to process data on a single record.

Generally, the cursor is used to locate a certain row of the result set for data modification.

Usage of cursor

1. Declare a cursor: declare cursor name CURSOR for table;(table here It can be any collection you query)

2. Open the defined cursor: open cursor name;

3. Get the next row of data:FETCH cursor Name into testrangeid,versionid;

4. Statements that need to be executed (add, delete, modify, check): This depends on the specific situation

5. Release the cursor:CLOSE Cursor name ;

Note: Each sentence of mysql stored procedure must end with;, and the temporary fields used need to be declared before defining the cursor.

Example

-  BEGIN  
  --定义变量  declare testrangeid BIGINT;  
declare versionid BIGINT;   
declare done int;  
--创建游标,并存储数据  declare cur_test CURSOR for   
   select id as testrangeid,version_id as versionid from tp_testrange;  
--游标中的内容执行完后将done设置为1  
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;   
--打开游标  open cur_test;  
--执行循环    posLoop:LOOP  
--判断是否结束循环  
        IF done=1 THEN    
      LEAVE posLoop;  
    END IF;   
--取游标中的值  
    FETCH  cur_test into testrangeid,versionid;  
--执行更新操作  
    update tp_data_execute set version_id=versionid where testrange_id = testrangeid;  
  END LOOP posLoop;  
--释放游标  CLOSE cur_test;  
  
END  -

Example 2:

We are now going to use a stored procedure to make a function to count the total inventory of iPhones What is the value and output the total to the console.

--在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 is to obtain the data row currently pointed by the cursor and point the pointer to the next row. Continuing execution when the cursor is already pointing to the last row will cause cursor overflow.
When using a loop cursor, it will not monitor whether it has reached the last piece of data. Writing the following code will cause an infinite loop;

read_loop:loop  
fetch cur into n,c;  
set total = total+c;  
end loop;

In MySql, when the cursor overflows MySQL's predefined NOT FOUND error will be triggered, so the following code is used above to specify a continue event when a not found error is raised, and to modify the value of the done variable when this event occurs.

declare continue HANDLER for not found set done = true;

So the following code is added to the loop:

--判断游标的循环是否结束  if done then  
    leave read_loop;    --跳出游标循环  end if;

If the value of done is true, end the loop. Continue to execute the following code

Usage methods

There are three ways to use cursors:

  • The first is the above implementation, using loop loop;

  • The second way is as follows, using a while loop:

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();

The third way is to use repeat execution:

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();

Cursor nesting

In mysql, each begin end block is an independent scope area. Since the same error event in MySql can only be defined once, if it is defined multiple times, When compiling, it will prompt 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();

The above is to implement a nested loop. Of course, this example is far-fetched. Just take a look.

Dynamic SQL

Mysql supports dynamic SQL functions

set @sqlStr='select * from table where condition1 = ?';  
prepare s1 for @sqlStr;  
--如果有多个参数用逗号分隔  execute s1 using @condition1;  
--手工释放,或者是 connection 关闭时, server 自动回收  deallocate prepare s1;

[Related recommendations: mysql video tutorial]

The above is the detailed content of What is the use of mysql cursor?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment