问题
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