如何知道插入查询是否在存储过程中成功?

时间:2014-05-17 15:57:38

标签: mysql sql stored-procedures

我正在编写一个存储过程来创建一个播放器:

CREATE PROCEDURE `create_player` (
firstName TEXT CHARACTER SET utf8,
lastName TEXT CHARACTER SET utf8,
username TEXT CHARACTER SET utf8,
password TEXT CHARACTER SET utf8,
email TEXT CHARACTER SET utf8,
gender ENUM('m','f'),
avatar INTEGER,
OUT result INTEGER)
BEGIN
DECLARE insertVal INTEGER DEFAULT 0;

INSERT INTO `Players` 
(`PlayerFirstName`, 
`PlayerLastName`, 
`PlayerName`, 
`PlayerPassword`, 
`PlayerEmail`,
`PlayerGender`, 
`PlayerAvatar`, 
`PlayerJoinDate`) VALUES (
 firstName,lastName,username,player_hash_password(password),email,gender,avatar,NOW());
END

假设我想让用户知道此插入是否成功,我怎样才能知道它是否成功(受影响的行数)。我试图将一个整数变量=设置为insert语句,但这不起作用。

存储过程的典型错误检查方法是什么?

3 个答案:

答案 0 :(得分:3)

根据ROW_COUNT()上的MySQL文档,

  

ROW_COUNT()返回上一个语句更改,删除或插入的行数(如果它是UPDATEDELETEINSERT。对于其他陈述,该值可能没有意义

insert语句后,您可以将row_count()读入OUT参数result。在调用程序中使用相同的result值,以便让用户知道受影响的行数。

按以下步骤更改您的程序

DROP PROCEDURE IF EXISTS `create_player`;

delimiter //

CREATE PROCEDURE `create_player` (
    firstName TEXT CHARACTER SET utf8,
    lastName TEXT CHARACTER SET utf8,
    username TEXT CHARACTER SET utf8,
    password TEXT CHARACTER SET utf8,
    email TEXT CHARACTER SET utf8,
    gender ENUM('m','f'),
    avatar INTEGER,
    OUT result INTEGER )
BEGIN
    DECLARE insertVal INTEGER DEFAULT 0;

    INSERT INTO `Players`(
        `PlayerFirstName`, 
        `PlayerLastName`, 
        `PlayerName`, 
        `PlayerPassword`, 
        `PlayerEmail`,
        `PlayerGender`, 
        `PlayerAvatar`, 
        `PlayerJoinDate`)
    VALUES (
        firstName, lastName, username, 
        player_hash_password( password ), 
        email, gender, avatar, NOW() );

    SELECT ROW_COUNT() INTO result;
END;

//

delimiter ;

答案 1 :(得分:0)

使用php代码可以帮助你

<?php  
    include("connect.php");//..your db connection file
    $result = mysql_query("SELECT * FROM Players"); 
    if (mysql_num_rows($result)){
       echo "Data entered successfully";
    }
    else
    {echo "failed";}

?>

答案 2 :(得分:0)

通过ExecuteNonQuery()方法插入数据时。此方法将数据库中受影响的行数返回为整数。

例如。

int i=0;
i= cmd.ExecuteNonQuery();
if( i >0)
 {
  msg ="Inserted Successfully";
 }
else
  msg="Not Inserted";