Hi guys. I need some help! I've been at work now for 36 hours (seen the same people come and go twice already!) and I've been stumped on a problem for a bit.

I'm trying to insert a row into a database and pull out the ID (primary key) that the database assigned automatically. I'm using DBI, but I tried the AddNew() func in ADODB.Recordset but that was no joy. Back to DBI now.

My original thought was insert the data and do a "Select MAX" on the primary key, but could end up worse than the race conditions you get in bad file-locking practices.


I am sure that there must be a way of doing this in DBI, but I can't see how - execute() returns 1 always (almost always)

It's starting to do my head in! I read through the DBI docs again but couldn't find anything - neither on usenet nor on PM Super Search. Although this could be due to my almost delirious hyper-caffeinated state. The answer is probably staring me in the face. Oh, I tried DBIx::Recordset and didn't like it much although I suspect it "might" be able to do what I want (sorry Terrence).

I appreciate any help available. Here's a bit of code I've munged over the past few hours... (I know its not terribly efficient at this stage but I'll fix that once I figure out how to do this primary key thing):
use DBI; # declared variables - dsn, etc... my @columns = keys %$input; my $columns = join ', ', @columns; my @values = map {$input->{$_} } @columns; my $vars = join ',', map { "?" } @columns; my $conn = DBI->connect($dsn, $user, $pass); my $sql = "Insert Into $table ($columns) values ($vars)"; my $sth = $conn->prepare($sql); $sth->execute(@values); # return $sth->{int_id} ?
Thank you guys

$ perldoc perldoc

In reply to DBI and primary keys by $code or die

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.