How can I fetch the last row I inserted using DBI?

南楼画角 提交于 2019-12-18 04:28:07

问题


How can I fetch the last row that was inserted using DBI (DBD::mysql)?

Code sample:

my $sth = $dbh->prepare('INSERT INTO a ( x, y, z ) VALUES ( ?, ?, ? )');
$sth->execute( $x, $y, $z );

How can I get access to the data that was inserted by the above prepare statement? I need to get the primary ID (AUTOINCREMENT) value.

UPDATE:

From DBD::mysql documentation:

An alternative way for accessing this attribute is via $dbh->{'mysql_insertid'}.

Thank you Manni and n0rd for your answers. :-)


回答1:


This is a property of the statement handle. You should be able to access the ID like that:

$sth->{mysql_insertid}



回答2:


A database agnostic approach is to use the DBI's last_insert_id method. This approach helps to reduce dependency on a specific database:

$dbh->last_insert_id

$rv = $dbh->last_insert_id($catalog, $schema, $table, $field);

Returns a value 'identifying' the row just inserted, if possible. Typically this would be a value assigned by the database server to a column with an auto_increment or serial type. Returns undef if the driver does not support the method or can't determine the value.




回答3:


SELECT LAST_INSERT_ID() query will also return what you want.



来源:https://stackoverflow.com/questions/1906896/how-can-i-fetch-the-last-row-i-inserted-using-dbi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!