Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

DBI and primary keys

by $code or die (Deacon)
on Mar 28, 2001 at 00:02 UTC ( #67607=perlquestion: print w/replies, xml ) Need Help??
$code or die has asked for the wisdom of the Perl Monks concerning the following question:

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

Replies are listed 'Best First'.
Re: DBI and primary keys
by lachoy (Parson) on Mar 28, 2001 at 00:21 UTC

    This really, really depends on the database you're using. MySQL uses AUTO_INCREMENT fields and DBD::mysql stores the value for the row just inserted in $dbh->{mysql_insertid}.

    Sybase and MS SQL Server use IDENTITY fields, which stores the value in your database connection session and you can retrieve the value using SELECT @@IDENTITY.

    Postgres uses a sequence to accomplish the same thing and you can either select the NEXTVAL from the sequence before you send the statement to the db and send the ID value or, if you use the SERIAL datatype you can SELECT CURRVAL( sequence-name ) and get the current sequence value.

    IIRC, Oracle uses sequences as well but I don't know the exact semantics.

    Or (plug plug) you can use SPOPS, which does this and a number of other things for you. Postgres support is in CVS and will be in the next version.

    M-x auto-bs-mode

      To get the number from a sequence in Oracle you can do a quick select like:
      my $sth = $dbh->prepare("select MY_SEQUENCE.NEXTVAL from DUAL");
      and this will give you the next number from Oracle. Dual is a magic table. It is there to ask the Database different questions.


      Learn patience, you must.
      Young PerlMonk, craves Not these things.
      Use the source Luke.
Re: DBI and primary keys
by busunsl (Vicar) on Mar 28, 2001 at 00:17 UTC
    I think DBI cannot help you here.
    This depends solely on the RDBMS.

    For Sybase ASE and mssql the following sql-statement should give you the correct value:

    select @@identity
(boo) Re: DBI and primary keys
by boo_radley (Parson) on Mar 28, 2001 at 00:19 UTC
    select @@identity should do the trick.

    now, go get some sleep, man.

      That did the trick! Thanks everyone. I'm off home now!!

      ++ all round!

      Update: I was using MS SQL by the way, but I also use mySQL so all the answers were very useful.

      $ perldoc perldoc
        Well, since the guts of MS SQL are Sybase (7. something, IIRC), the @@identity thing makes sense.
        Jay "Yohimbe" Thorne, alpha geek for UserFriendly
Re: DBI and primary keys
by mr.nick (Chaplain) on Mar 28, 2001 at 00:14 UTC
    At least in MySQL, to retrieve the ID of the most recently inserted row, use LAST_INSERT_ID() ala:
    select LAST_INSERT_ID();
      Or, futhermore:     my ($last_id) = $db->selectrow_array("SELECT LAST_INSERT_ID()");
        But what if this is multiprocess where there might be two or three inserts that go in at (or close to) the same time? I might end up with the same "last row" for each of them?

        $ perldoc perldoc
      Knowing which database you are using would help. Also available, at least with mySQL:

Re: DBI and primary keys
by wardk (Deacon) on Mar 28, 2001 at 03:09 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://67607]
Approved by root
[1nickt]: 'morning Monks :-)

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2017-10-19 10:19 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (252 votes). Check out past polls.