Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Retrieving the last insert ID with Access

by simon.proctor (Vicar)
on Jul 23, 2001 at 14:25 UTC ( #98956=snippet: print w/ replies, xml ) Need Help??

Description: Based on the help I had with a question last week, heres how to get the last insert ID from an access database using the recordset. This is Windows only.

If you are ever unfortunate enough to have to use Access then this should help you no end (it has for me :P)
        use Win32::OLE;
        use constant adOpenKeySet => 1;
        use constant adLockPessimistic => 2;
        use constant adCmdTable => '&H0002';

        my $db_connection = new Win32::OLE('ADODB.Connection');
    
        # Set the database connection details
        my $db_datasource = 'Driver={Microsoft Access Driver (*.mdb)};
+';
          $db_datasource .= 'DBQ=classifieds.mdb';
    
        # Connect to the database and tie the recordset object to the 
+database.
        $db_connection->Open($db_datasource);

        my $rs = new Win32::OLE("ADODB.Recordset");

        # you're going to have to define your consts that
        # you're using in the vbscript example
        $rs->Open('ADS', $db_connection, adOpenKeySet, adLockPessimist
+ic, adCmdTable);
        $rs->AddNew();
        $rs->{'title'}{'Value'} = 'Ad title';
        $rs->{'posted_by'}{'Value'} = 'Simon Proctor';
        $rs->{'date_authorised'}{'Value'} = 0;
        $rs->Update();
        my $last_id = $rs->{'ID'}{'Value'};
        $rs->close();
        $db_connection->close();
Comment on Retrieving the last insert ID with Access
Download Code
Re: Retrieving the last insert ID with Access
by Tortue (Scribe) on Jul 23, 2001 at 17:42 UTC
    Thanks that's actually a problem I've encountered a few times. <idle_wish>It's common enough (and different enough in each DBMS) that a DBI function for this would be nice.</idle_wish> Oh and a link to the original discussion would be handy too.

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2014-08-20 13:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (113 votes), past polls