1

我在遵循 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
4

1 回答 1

2
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;
于 2013-04-16T03:54:02.493 回答