Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Autoincrement and server hostname in DB2

by Anonymous Monk
on Oct 06, 2000 at 23:03 UTC ( [id://35640]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm using DB2 with Perl's DBI and I have two questions that should have easy answers.

  1. When I have an autoincrementing field, how can I get the ID that was generated by my last insert?
  2. Is there a way to get the hostname of the database server from a DBI method?

Any help would be greatly appreciated!

  • Comment on Autoincrement and server hostname in DB2

Replies are listed 'Best First'.
Re: Autoincrement and server hostname in DB2
by ncw (Friar) on Oct 06, 2000 at 23:27 UTC
    There isn't a DBI standard method of getting the id of a last autoincremented id as far as I know. I think this is because not all databases support this method of doing things.

    That said I know how to do this in MySQL. After you have done

    $cursor = $dbh->prepare("insert into table (a, b) values (?, ?)"); $cursor->execute($a_var, $b_var);
    You can then read the last autoincrementid using a MySQL extension
    $id = $dbh->{mysql_insertid};
    This variable is related to your dbh session so it is safe in the presence of multiple updaters.

    In a previous version of DBD::mysql the variable was just $dbh->{insertid}.

    Don't try to get the last inserted id by "select max(id) from table" this will work short term, but get you into no end of trouble later. You could make it work by locking the table before your insert I guess.

    It would be useful if this was standardised in DBI if possible. I personally build all my tables using autoincrementing id's and $dbh->{mysql_insertid} for joining them.

    Look at your documentation for DBD::DB2 and see if it offers anything similar!

Re: Autoincrement and server hostname in DB2
by Anonymous Monk on Oct 07, 2000 at 01:48 UTC

    Okay, a co-worker of mine finally tracked down the answer. Just posting here in case any one else is interested in the answer:

    1. Turn off auto-commit ($dbh->{'AutoCommit'} = 0)
    2. Do insert
    3. SELECT id FROM table WHERE id = INTEGER(IDENTITY_VAL_LOCAL())
    4. Commit changes

    Naturally, id is the field that is auto-incremented and table is the table you just inserted into.

    Share and Enjoy.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 19:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found