SkipHuffman has asked for the wisdom of the Perl Monks concerning the following question:
Basically I need to know the autoincremented "id" value from row that I am inserting into a table. How can I get this?
I have tried the "last_insert_id" function, but I really don't trust it. I could get into a race condition if a second row were inserted before I could retrieve the id from the row that I just inserted.
Here is what I have tried. Perhaps I just don't have last_insert_id working properly. (it is returning null at the moment.)
my $query; $query=qq(insert into MasterEpisode set \ ShowId ="$ShowID",\ title ="$p->{'ep_title'}",\ description ="$p->{'ep_description'}",\ uploaddate =localtime ); print p($query); $dbh->do("$query"); # I see a risk of a race condition here. I should see +if I can get the ID while I insert the line. my $episodeid=$dbh->last_insert_id(undef,undef,"MasterEpisode" +,undef); print p("Episode id is $episodeid.");
Ok, looks like I can make it work in MySQL by doing this
# $episodeid=$dbh->last_insert_id(undef,undef,'MasterEpisode', +undef); $sth = $dbh->prepare(qq(select LAST_INSERT_ID() from MasterEpi +sode)); $sth->execute(); @episodeid=$sth->fetchrow_array(); $episodeid=$episodeid[0]; print p("Episode id is $episodeid.");
But it looks ugly and non portable to me.
|
|---|