PerlのDBIでINSERT処理をした時に、新たに作成したレコードのIDを取得したい時がある。
INSERTしたレコードのIDを取得する方法
もし、あなたがDBI::mysql
のモジュールを使っている場合は、以下のように$sth->{mysql_insertid}
を使えば新規レコードのIDを取得できる。
my $sth = $db->prepare($sql); $sth->execute; my $id = $sth->{mysql_insertid};
この$sth->{mysql_insertid}
が使えるのは、以下の2つの条件を満たした時となる。
- INSERT文を実行した時。
- INSERTしたテーブルに、AUTO_INCREMENTカラムが1つ存在する
多くの場合はid
カラムをAUTO_INCREMENTとして作成していると思うので、上記の2つの条件は満たすと思う。
公式ドキュメントには、以下のように書かれている。(太字は著者)
If the statement you executed performs an INSERT, and there is an AUTO_INCREMENT column in the table you inserted in, this attribute holds the value stored into the AUTO_INCREMENT column, if that value is automatically generated, by storing NULL or 0 or was specified as an explicit value.
Typically, you’d access the value via $sth->{mysql_insertid}. The value can also be accessed via $dbh->{mysql_insertid} but this can easily produce incorrect results in case one database handle is shared.
DBD::mysql – MySQL driver for the Perl5 Database Interface (DBI) – metacpan.org