当前位置:网站首页>What is the function of MySQL cursors
What is the function of MySQL cursors
2022-06-29 17:23:00 【Yisu cloud】
mysql What is the function of a cursor
Today I'd like to share with you mysql What is the function of the cursor , Detailed content , Clear logic , I believe most people still know too much about this knowledge , So share this article for your reference , I hope you will gain something after reading this article , Now let's take a look .
stay mysql in , Cursor has the function of pointer , It is mainly used to traverse the record result set returned by the query database , In order to carry out the corresponding operation . A cursor is actually a mechanism that can extract one record at a time from a result set that contains multiple data records . The essence of RDBMS is set oriented , stay MySQL There is no representation in the table that describes a single record in the table , Unless used WHERE Clause to restrict only one record to be selected ; So sometimes we must use the cursor to process the data of a single record .
The operating environment of this tutorial :windows7 System 、mysql8 edition 、Dell G3 The computer .
MySQL The cursor (Cursor)
A cursor is actually a mechanism that can extract one record at a time from a result set that contains multiple data records .
The cursor acts as a pointer .
Although the cursor can traverse all the rows in the result , But he only points to one line at a time .
The function of cursor is to traverse the records returned by query database , In order to carry out the corresponding operation .
The essence of RDBMS is set oriented , stay MySQL There is no representation in the table that describes a single record in the table , Unless used WHERE Clause to restrict only one record to be selected . So sometimes we must use the cursor to process the data of a single record .
Generally, data modification is performed by locating the cursor to a row of the result set .
Usage of cursors
1、 Declare a cursor : declare Cursor name CURSOR for table;( there table It can be any set you query out )
2、 Open 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 ( Additions and deletions ): It depends on the circumstances
5、 Release cursor :CLOSE Cursor name ;
notes :mysql The stored procedure must be followed by ; ending , The temporary fields used need to be declared before the cursor is defined .
example
- BEGIN -- Defining variables declare testrangeid BIGINT; declare versionid BIGINT; declare done int; -- Create cursors , And store data declare cur_test CURSOR for select id as testrangeid,version_id as versionid from tp_testrange; -- After the contents of the cursor are executed, the done Set to 1 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; -- Open cursor open cur_test; -- Execute loop posLoop:LOOP -- Determine whether to end the loop IF done=1 THEN LEAVE posLoop; END IF; -- Take the value in the cursor FETCH cur_test into testrangeid,versionid; -- Perform an update operation update tp_data_execute set version_id=versionid where testrange_id = testrangeid; END LOOP posLoop; -- Release cursor CLOSE cur_test; END -
Example 2:
Now we're going to do a function with stored procedures , Statistics iphone What's the total stock of , And output the total to the console .
-- stay windows When writing stored procedures in the system , If needed declare Declare variables , You need to add this keyword , Otherwise, an error will be reported . delimiter // drop procedure if exists StatisticStore; CREATE PROCEDURE StatisticStore() BEGIN -- Create variables to receive cursor data declare c int; declare n varchar(20); -- Create a total variable declare total int default 0; -- Create an end flag variable declare done int default false; -- Create cursors declare cur cursor for select name,count from store where name = 'iphone'; -- Specifies the return value at the end of the cursor loop declare continue HANDLER for not found set done = true; -- Set initial value set total = 0; -- Open cursor open cur; -- Start looping through the data in the cursor read_loop:loop -- According to a piece of data that the cursor currently points to fetch cur into n,c; -- Determine whether the cursor's loop ends if done then leave read_loop; -- Jump out of the cursor loop end if; -- When getting a piece of data , take count Value to be accumulated , Here you can do whatever you want , set total = total + c; -- End cursor loop end loop; -- Close cursor close cur; -- Output results select total; END; -- Calling stored procedure call StatisticStore();
fetch Is to get the data row that the cursor currently points to , And point the pointer to the next line , Continuing to execute when the cursor has already pointed to the last row will cause cursor overflow .
Use loop When you cycle the cursor , He doesn't monitor the last data himself , Like the following code , It's going to create a dead cycle ;
read_loop:loop fetch cur into n,c; set total = total+c; end loop;
stay MySql in , Causes a cursor overflow mysql Predefined NOT FOUND error , So use the following code above to specify when to raise not found Define a... When it's wrong continue Events , Specifies to modify when this event occurs done The value of the variable .
declare continue HANDLER for not found set done = true;
So I added the following code in the loop :
-- Determine whether the cursor's loop ends if done then leave read_loop; -- Jump out of the cursor loop end if;
If done The value of is true, Just close the loop . Continue with the following code
Usage mode
There are three ways to use cursors :
The first is the above implementation , Use loop loop ;
The second way is as follows , Use 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 perform :
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
stay mysql in , Every begin end The blocks are all independent scope Area , because MySql The same one error Can only be defined once , If there are multiple definitions, you will be prompted at compile time 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 make do with it .
dynamic SQL
Mysql Support dynamic SQL The function of
set @sqlStr='select * from table where condition1 = ?'; prepare s1 for @sqlStr; -- If there are multiple arguments separated by commas execute s1 using @condition1; -- Release by hand , Or is it connection closed , server Automatic recovery deallocate prepare s1;
That's all “mysql What is the function of a cursor ” All the content of this article , Thank you for reading ! I believe you will gain a lot after reading this article , Xiaobian will update different knowledge for you every day , If you want to learn more , Please pay attention to the Yisu cloud industry information channel .
边栏推荐
- LeetCode 每日一题——535. TinyURL 的加密与解密
- “授权同意”落地压力大?隐私计算提供一种可能的合规“技术解”
- Master slave replication of MySQL
- 力扣今日题-535. TinyURL 的加密与解密
- mysql数据库扫盲,你真的知道什么是数据库嘛
- Interrupt怎么用
- PCB frame drawing - ad19
- 为什么信息化 ≠ 数字化?终于有人讲明白了
- The fixed assets management system enables enterprises to dynamically master assets
- sequential detector
猜你喜欢

Calibration of monocular camera and binocular camera with kalibr calibration tool

In depth analysis of Monai (I) data and transforms

Leetcode daily question - 535 Encryption and decryption of tinyurl

Shenzhen internal promotion | Shenzhen Institute of computing science recruits assistant machine learning Engineer (school recruitment)

如何创建虚拟形象

mysql.sock的概念是什么

基于汇编实现的流载体的LSB隐藏项目

【R语言数据科学】:文本挖掘(以特朗普推文数据为例)

Subgraphs in slam

mysql在linux中2003错误如何解决
随机推荐
535. TinyURL 的加密与解密 / 剑指 Offer II 103. 最少的硬币数目
Redis principle - sorted set (Zset)
在供应链场景应用中,供应链管理系统扮演什么角色?
序列检测器
R语言使用MASS包的glm.nb函数建立负二项广义线性模型(negative binomial)、summary函数获取负二项广义线性模型模型汇总统计信息
regular expression
有遇到用flink-cdc采集MySQL-RDS的时候,datetime类型的字段,采集过来后和源表
Epoll analysis
PCB frame drawing - ad19
mysql在linux中2003错误如何解决
NVIDIA安装最新显卡驱动
@Difference between component and @configuration
Why is informatization ≠ digitalization? Finally someone made it clear
Freedom自由协议质押挖矿系统开发
mysql如何查询表的字符集编码
SAAS 服务的优势都有哪些
Scenario solution for two modules calling each other in go
Bags of Binary Words for Fast Place Recognition in Image Sequenc
Help MySQL data analysis with databend
0基础自学STM32(野火)——使用寄存器点亮LED——GPIO功能框图讲解