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

后端 未结 3 369
臣服心动
臣服心动 2020-12-17 07:39

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 ( ?         


        
相关标签:
3条回答
  • 2020-12-17 08:27

    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.

    0 讨论(0)
  • 2020-12-17 08:34

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

    $sth->{mysql_insertid}
    
    0 讨论(0)
  • 2020-12-17 08:41

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

    0 讨论(0)
提交回复
热议问题