mysql @@identity 与 sql-server last_insert_id()

发布于 2024-08-20 01:54:07 字数 332 浏览 3 评论 0原文

我是否正确地理解mysql的LAST_INSERT_ID()函数不会在插入尝试之间重置(就像@@identity在sql-server中所做的那样)...如果前一个插入操作失败,LAST_INSERT_ID()将返回任何内容的pk该连接最后一次插入任何具有自动递增主键的表的 pk 是。如果我的观点是正确的,那么这似乎不是人们可以想到的该函数中最迟钝的行为吗?是否没有 mysql 函数的行为与 sql-server 的 @@identity 类似?如果紧接在前的插入尝试没有创建新记录,则返回 NULL?或者,如何确定地知道最近插入操作的主键?

Am I correct in understanding that mysql's LAST_INSERT_ID() function doesn't reset between insert attempts (as @@identity does in sql-server)... that if the immediately preceding insert operation fails, LAST_INSERT_ID() will return the pk of whatever the pk of that connection's last insert to any table with an auto-incrementing primary key was. And if I am correct in this, does this not seem like just about the most retarded behaviour for this function that one could come up with? Is there no mysql function that behaves similarly to sql-server's @@identity? One that will return NULL if the immediately preceding insert attempt creates no new record? Alternatively, how does one know with certainty the primary key of the most recent insert operation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄情伤 2024-08-27 01:54:07

@@identity 在 sql server 中通常也是错误的。在大多数情况下,您应该使用 scope_identity()

在 MySql 中,last_insert_id() 应该可以安全使用,因为在插入错误后调用此函数的唯一方法是您已经正确捕获并解释了插入错误。否则你仍然会处理命令。换句话说,last_insert_id() 不是您的错误处理机制。

@@identity is usually wrong in sql server as well. You should be using scope_identity() in most cases instead.

In MySql, last_insert_id() should be safe to use because the only way you can call this function after an insert error is you've already correctly caught and accounted for the insert error. Otherwise you would still be processing commands. In other words, last_insert_id() is not your error-handling mechanism.

巷雨优美回忆 2024-08-27 01:54:07

您必须先检查插入是否成功。如果插入成功,那么您可以依赖 LAST_INSERT_ID()。

编辑:在 PHP 中:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query('<PUT YOUR INSERT HERE');
if(mysql_affected_rows()>0){
  $last_id=mysql_insert_id();
}else{
  //panic!
}
?>

You have to check to see if the insert was successful first. If the insert was successful, then you can rely on LAST_INSERT_ID().

edit: in php:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query('<PUT YOUR INSERT HERE');
if(mysql_affected_rows()>0){
  $last_id=mysql_insert_id();
}else{
  //panic!
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文