mysql游标未打开

时间:2013-04-16 03:44:45

标签: mysql

Iam在跟踪MySql存储过程时遇到问题,当我尝试从控制台和应用程序运行它时,它给出了一个SQLException,说光标没有打开,有人可以告诉我为什么它没有打开?

 DELIMITER $$
DROP PROCEDURE IF EXISTS DELETE_EXPIRED_GIFTS_SP$$
CREATE PROCEDURE DELETE_EXPIRED_GIFTS_SP()
    BEGIN
    DECLARE gift_id_val INT;
    DECLARE item_id_val INT;   
    DECLARE expiry_date DATETIME;
    DECLARE  no_more_gifts INT DEFAULT 0;
    DECLARE num_rows INT DEFAULT 0;
    DECLARE  gift_items_cur CURSOR FOR 
        SELECT user_gift_id, item_id
        FROM user_gift
        WHERE status in (1,3);

    DECLARE  CONTINUE HANDLER FOR NOT FOUND 
    SET  no_more_gifts = 1;

    OPEN gift_items_cur;
        select FOUND_ROWS() into num_rows;
        the_loop: LOOP
            FETCH  gift_items_cur  INTO   gift_id_val, item_id_val;

            IF no_more_gifts=1 THEN
                    CLOSE gift_items_cur;
                    LEAVE the_loop;
            END IF;

            SELECT end_time INTO expiry_date FROM item WHERE item_id = item_id_val;

            IF expiry_date IS NOT NULL AND expiry_date <= UTC_TIMESTAMP()
                THEN UPDATE user_gift SET status = 5 WHERE user_gift_id = gift_id_val;
            END IF;

         END LOOP the_loop;
    CLOSE  gift_items_cur;
    END$$
 DELIMITER ;

我遇到的错误是,

  09:05:31,328 INFO  [STDOUT] FATAL: com.abc.gift.support.impl.GiftSupportImpl - ERROR: CallableSt
atementCallback; uncategorized SQLException for SQL [{call DELETE_EXPIRED_GIFTS_SP()}]; SQL state [2
4000]; error code [1326]; Cursor is not open; nested exception is java.sql.SQLException: Cursor is n
ot open

1 个答案:

答案 0 :(得分:1)

the_loop: LOOP
    :
    IF no_more_gifts=1 THEN
        CLOSE gift_items_cur;      <<< Number 1
        LEAVE the_loop;
    END IF;
    :
END LOOP the_loop;
CLOSE  gift_items_cur;             <<< Number 2

在我看来,你正在关闭光标两次

您在处理程序激活且no_more_gifts设置为1后第一次关闭它。此时,您也退出循环,然后再次尝试关闭光标

我建议将内部if语句改为:

IF no_more_gifts=1 THEN
    LEAVE the_loop;
END IF;