Perl DBI で INSERT 後のIDを取得する

概要

PerlではDBIの同一ハンドルでINSERTを実行し、使用中のドライバーが提供するlast_insert_idを利用します。SQL文字列の連結は避けます。

実施例

my $sth = $dbh->prepare('INSERT INTO entries (title) VALUES (?)');
$sth->execute($title);
my $id = $dbh->last_insert_id(undef, undef, 'entries', 'id');

注意点

last_insert_idの対応範囲はDBドライバーに依存します。対象DBでテストし、トランザクションの接続を途中で切り替えないでください。

参考: 公式ドキュメント

Comments