MySQL completely disintegrated 19: cursor related

Weng Zhihua 2021-01-21 16:21:25
mysql completely disintegrated cursor related


Definition

We often come across a situation like this , We need to traverse the results of our query , And to traverse to each data processing , In this case, the cursor will be used .
therefore : The cursor (Cursor) It's a way to process data stored in MySQL Database query method on the server , In order to view or process the data in the result set , Provides the ability to traverse data one line at a time in the result set .
Cursors are mainly used for loop processing 、 stored procedure 、 function 、 trigger in .

The function of cursors

Like the one above us students Student , Each user needs to be traversed , Then add or subtract points based on their other evaluations . At this time, we need to query all the students' information ( Include grades ).
1 select studentid,studentname,score from students; 
The student data set returned after execution , If we need to traverse the student data one by one , Then add points according to the specific situation , Then you need to use a cursor .
A cursor is equivalent to a pointer , This pointer points to select First row of data for , You can traverse the following data by moving the pointer . 

The use of cursors

declare cursor : Create a cursor , And specify what the cursor needs to traverse select Inquire about , When you declare a cursor, you don't execute this sql.
Open cursor : When opening the cursor , Will execute the cursor corresponding to select sentence .
Traversal data : Use the cursor loop to traverse select Each row of data in the result , And then deal with it .
Business operations : The process of operating on each row of data traversed , You can place any executed statement that needs to be executed ( Additions and deletions ): It depends on the circumstances
Close cursor : The cursor must be released after use .
notes : The temporary fields used need to be declared before the cursor is defined .

declare cursor

1 DECLARE cursor_name CURSOR FOR select_statement; 
Declare a cursor . You can also define multiple cursors in a subroutine , But every cursor in a block must have a unique name . After the cursor is declared, it is also a single operation , however SELECT Statement cannot have INTO Clause .
One begin end Only one cursor can be declared in .

Open cursor

1 OPEN cursor_name; 
Open the previously declared cursor .

Traversing cursor data

1 FETCH cursor_name INTO var_list;
This statement reads the next line with the specified open cursor ( If there's a next line ), And forward cursor pointer . Take the result of the current line , Put the result in the corresponding variable , And the cursor pointer to the next row of data .
When calling fetch When , Will get the data of the current row , If the current row has no data , May trigger mysql Inside NOT FOUND error .

Close cursor

1 CLOSE cursor_name; 
Remember to close the cursor after use .

Cursor example

Write a function , It contains right students Calculation of student user scores and additional points
Data base
 1 mysql> select * from students;
 2 +-----------+-------------+-------+---------+
 3 | studentid | studentname | score | classid |
 4 +-----------+-------------+-------+---------+
 5 | 1 | brand | 97.5 | 1 |
 6 | 2 | helen | 96.5 | 1 |
 7 | 3 | lyn | 96 | 1 |
 8 | 4 | sol | 97 | 1 |
 9 | 5 | b1 | 81 | 2 |
10 | 6 | b2 | 82 | 2 |
11 | 7 | c1 | 71 | 3 |
12 | 8 | c2 | 72.5 | 3 |
13 | 9 | lala | 73 | 0 |
14 | 10 | A | 99 | 3 |
15 | 16 | test1 | 100 | 0 |
16 | 17 | trigger2 | 107 | 0 |
17 | 22 | trigger1 | 100 | 0 |
18 +-----------+-------------+-------+---------+
19 13 rows in set 
Write functions that contain cursors

The notes here are very clear , Key knowledge points have been marked in red

 1 mysql>
 2 /* If the judgment function exists, it will be deleted */
 3 DROP FUNCTION IF EXISTS fun_test;
 4 /* The declaration terminator is $*/
 5 DELIMITER $
 6 /* Create a function , Add points to each student who meets the requirements , The added score cannot exceed the given value max_score*/
 7 CREATE FUNCTION fun_test(max_score decimal(10,2))
 8 RETURNS int
 9 BEGIN
10 /* Define real time StudentId The variable of */
11 DECLARE var_studentId int DEFAULT 0;
12 /* Define the variables of the calculated fraction */
13 DECLARE var_score decimal(10,2) DEFAULT 0;
14 /* Define the cursor end flag variable */
15 DECLARE var_done int DEFAULT FALSE;
16 /* Create cursors */
17 DECLARE cur_test CURSOR FOR SELECT studentid,score from students where classid<>0;
18 /* At the end of the cursor var_done by true, Can be used later var_done To determine whether the cursor ends */
19 DECLARE CONTINUE HANDLER FOR NOT FOUND SET var_done=TRUE;
20 /* Open cursor */
21 OPEN cur_test;
22 /* Use Loop Loop through cursor */
23 select_loop:LOOP
24 /* First get the data of the current row , Then put the data of the current row into var_studentId,var_score in , If there is no data line ,var_done Will be set to true*/
25 FETCH cur_test INTO var_studentId,var_score;
26 /* adopt var_done To determine if the cursor is over , Exit loop */
27 IF var_done THEN
28 LEAVE select_loop;
29 END IF;
30 /* Yes var_score Values add random values , No more than the given score */
31 set var_score = var_score + LEAST(ROUND(rand()*10,0),max_score);
32 update students set score = var_score where studentId= var_studentId;
33 END LOOP;
34 /* Close cursor */
35 CLOSE cur_test;
36 /* Return results : You can return the required content according to the actual situation */
37 RETURN 1;
38 END $
39 /* The ending character is set to ;*/
40 DELIMITER ;
41 Query OK, 0 rows affected
Call function
1 mysql>
2 /* Parameter is 8, The upper limit of bonus is 8 */
3 select fun_test(8);
4 +-------------+
5 | fun_test(8) |
6 +-------------+
7 | 1 |
8 +-------------+
9 1 row in set
View results

Compared with the original score value , I found that the score added a random value , But not more than a given score 8

 1 mysql> select * from students;
 2 +-----------+-------------+-------+---------+
 3 | studentid | studentname | score | classid |
 4 +-----------+-------------+-------+---------+
 5 | 1 | brand | 105.5 | 1 |
 6 | 2 | helen | 98.5 | 1 |
 7 | 3 | lyn | 97 | 1 |
 8 | 4 | sol | 97 | 1 |
 9 | 5 | b1 | 89 | 2 |
10 | 6 | b2 | 90 | 2 |
11 | 7 | c1 | 76 | 3 |
12 | 8 | c2 | 73.5 | 3 |
13 | 9 | lala | 73 | 0 |
14 | 10 | A | 100 | 3 |
15 | 16 | test1 | 100 | 0 |
16 | 17 | trigger2 | 107 | 0 |
17 | 22 | trigger1 | 100 | 0 |
18 +-----------+-------------+-------+---------+
19 13 rows in set
Check the trigger log

Those who meet the conditions to be modified are 9 Data , It has been recorded in the log by trigger

 1 mysql>
 2 /* Last one  Write triggers , When modifying students The log record is triggered when the table is opened */
 3 select * from triggerlog;
 4 +----+--------------+---------------+-----------------------------------------+
 5 | id | trigger_time | trigger_event | memo |
 6 +----+--------------+---------------+-----------------------------------------+
 7 | 1 | after | insert | new student info,id:21 |
 8 | 2 | after | update | update student info,id:21 |
 9 | 3 | after | update | delete student info,id:21 |
10 | 4 | after | update | from:test2,101.00 to:trigger2,106.00 |
11 | 5 | after | update | from:trigger2,106.00 to:trigger2,107.00 |
12 | 6 | after | update | delete student info,id:11 |
13 | 7 | after | update | from:brand,97.50 to:brand,105.50 |
14 | 8 | after | update | from:helen,96.50 to:helen,98.50 |
15 | 9 | after | update | from:lyn,96.00 to:lyn,97.00 |
16 | 10 | after | update | from:sol,97.00 to:sol,97.00 |
17 | 11 | after | update | from:b1,81.00 to:b1,89.00 |
18 | 12 | after | update | from:b2,82.00 to:b2,90.00 |
19 | 13 | after | update | from:c1,71.00 to:c1,76.00 |
20 | 14 | after | update | from:c2,72.50 to:c2,73.50 |
21 | 15 | after | update | from:A,99.00 to:A,100.00 |
22 +----+--------------+---------------+-----------------------------------------+
23 15 rows in set  
Cursor execution
Follow the example above , Analyze the execution process of this cursor .
1、 We created a cursor , The data source is from student Student list .
2、 There's a pointer in the cursor , When opening the cursor , Will execute the cursor corresponding to select sentence , This pointer will point to select The first line in the result records .
3、 When calling fetch Cursor name , Will get the data of the current row , If the current row has no data , Will trigger NOT FOUND abnormal .
When triggered NOT FOUND When out of the ordinary , We can use a variable to mark , As above :DECLARE CONTINUE HANDLER FOR NOT FOUND SET var_done=TRUE;
Put the variable var_done The value of is set to TURE, You can go through... In a cycle var_done The value of controls the exit of the loop :LEAVE select_loop;.
If the current row has data , Then save the current row data to the corresponding variable , And point the cursor pointer to the next row of data , Following statements :FETCH cur_test INTO var_studentId,var_score;

summary

1、 Cursors are used to traverse query results .
2、 How to use the cursor : declare cursor 、 Open cursor 、 Traversal cursor 、 Close cursor .
3、 Cursors are mainly used for loop processing 、 stored procedure 、 Use in a function , Used to query the result set .
4、 The disadvantage of cursors is that they can only operate line by line , In case of large amount of data , Not applicable , Too slow . Most databases are set oriented , The business will be more complicated , There will be deadlock when using cursor , Affect other business operations , Not an option . When the amount of data is large , Using cursors can cause out of memory .

 

 

 

版权声明
本文为[Weng Zhihua]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121162041062i.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云