MySQL Cursor

来源:http://www.cnblogs.com/kungfupanda/archive/2016/09/15/5874184.html
-Advertisement-
Play Games

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 SELE ...


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 iterate a 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 variable declaration. 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 Steps

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.


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • swift字典 在swift中,key:key值一定是可hash的,一定是獨一無二的,swift的基本數據類型(String,Int,Float)都是可哈希的,所以都可以作為key值。 value:沒有要求 直接上代碼了,註釋給大家標的很明白 //創建字典並賦值 let dict = ["name" ...
  • 博客: Android 6.0 運行時許可權管理最佳實踐 github: https://github.com/yanzhenjie/AndPermission ...
  • EventBus是最近項目用到的,也只是會些簡單的功能,不過感覺功能蠻強大的。代碼鏈接:http://download.csdn.net/detail/qq_29774291/9629346 EventBus是Guava的事件處理機制,是設計模式中的觀察者模式(生產/消費者編程模型)的優雅實現。主要 ...
  • 1、基本概念 2、創建 3、插入 4、查詢 5、封裝 6、model 7、界面顯示 存數據 ...
  • Animation 效果 用法 1.非常簡單,導入兩個文件(UIView+SetRect) (UIView+ImageEffects) 源碼 github源碼:https://github.com/makingitbest/Animation 細節 1.下圖是效果圖的全部代碼 ...
  • Usage xml android:background= ?attr/zzbackground app:backgroundAttr= zzbackground //如果當前頁面要立即刷新,這裡傳入屬性名稱 比如R.attr.zzbackground 傳zzbackground即可 android ...
  • http://www.cnblogs.com/cookiehu/p/4994278.html 定義異常捕獲類型及處理方法: 這裡面需要註意幾點: a、condition_value [,condition_value],這個的話說明可以包括多種情況(方括弧表示可選的),也就是一個handler可以定 ...
  • http://www.java2s.com/Code/SQL/Cursor/Outputdatainacursor.htm ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...