概要
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
PHP で、直近の INSERT で生成された ID を得るには?