Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: DBI insert: Need to retrieve an autoincremented column from a table after an insert.

by injunjoel (Priest)
on Aug 10, 2008 at 02:52 UTC ( [id://703367]=note: print w/replies, xml ) Need Help??


in reply to DBI insert: Need to retrieve an autoincremented column from a table after an insert.

Greetings,
One idea, though probably not the most efficient, would be to create two prepared statements, one for insert and another for query.
use DBI; #connection stuff #prepare your statement handles #assuming the values are unique enough... my $sth_ins = $dbh->prepare("INSERT INTO table_foo(col1,col2,col3) VAL +UES(?,?,?)"); #after the insert run the query on those same values. my $sth_sel = $dbh->prepare("SELECT id FROM table_foo WHERE col1=?, co +l2=?, col3=?"); #...later in the code... my $last_id; for(@some_data_of_yours){ $sth_ins->execute($_->{'col1'},$_->{'col2'},$_->{'col3'}); $sth_sel->execute($_->{'col1'},$_->{'col2'},$_->{'col3'}); $sth_sel->bind_columns(\$last_id); $sth_sel->fetch(); #do some stuff with your $last_id... }
Seems like overkill but at least you can trust the results. Basically a "Read it back to me" strategy.
Not sure how much load this will add to things but since the statements are prepared you get all of those benefits. You can also use the select statement as a pre-check to see if the data is already in the DB. Just a thought...

-InjunJoel
"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo
  • Comment on Re: DBI insert: Need to retrieve an autoincremented column from a table after an insert.
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://703367]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-18 12:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found