简体   繁体   English

在mysql存储过程中返回插入记录的ID

[英]return id of inserted record in mysql stored procedure

I created stored procedure to insert data and I want to get the id of inserted record in same procedure 我创建了存储过程来插入数据,我想在同一过程中获取插入记录的ID

DELIMITER $$

USE `dbname`$$

DROP PROCEDURE IF EXISTS `sp1`$$

CREATE DEFINER=`root`@`%` PROCEDURE `sp1`(
    Cname VARCHAR(30),
    Camount INT(10)

)
BEGIN
    INSERT INTO user(    Username,    PAmount    )
VALUES(    Cname,    Camount)    ;

    END$$

DELIMITER ;

I tried 我试过了

SELECT MAX(id) AS pid FROM user;

but this cause error in next query 但这在下一个查询中导致错误

error : Commands out of sync; you can't run this command now 错误: Commands out of sync; you can't run this command now Commands out of sync; you can't run this command now

If you get Commands out of sync; 如果命令不同步; you can't run this command now in your client code, you are calling client functions in the wrong order. 您现在无法在客户端代码中运行此命令,您以错误的顺序调用了客户端函数。

From here: http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html 从这里: http : //dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html

If the id is declared as a primary key , make use of last_insert_id() function which will resolve the issue. 如果将id声明为主键,请使用last_insert_id()函数来解决此问题。 For more details refer to last_insert_id() in mysql documentation 有关更多详细信息,请参考mysql文档中的last_insert_id()。

https://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id https://dev.mysql.com/doc/refman/5.0/zh-CN/information-functions.html#function_last-insert-id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM