PDA

View Full Version : Returning autoincremented number of insert


vlet
12-30-01, 04:30 AM
I'm actually writing this in perl, but I can just translate it...

in a table on my DB, I have a few fields that store whatever data, but the first field is an autoincremented unique number, so when I execute an INSERT statement to add a record, I do not have to include that particular field - it is fileld in by the DB. Does anyone know how I can retrieve that number without executing a SELECT statement - The Autoincremented ID is the only thing that keeps the records unique from one another, so I would not be able to find the ID by searching a different field.

I'm guessing it has something to do with the statement handle, but I don't know the way to retrieve it.

Any help would be appreciated - Thanks!

cjdj
12-30-01, 06:47 AM
First, I recommend that you download mySQL for your operating system (Windows presumably) and it includes a client app and some very handy documentation which gives some needed instructions on how to use with Perl, C and other stuff. Browse thru the doc (its actually very large) and you might see some other cool stuff in there you didn't know it could do.

But to answer your specific question, I will include an example:

assuming you have already connected to the database, and $dbh is the handle to the database.

my ($sth) = dbExecute($dbh, "insert into sampleTable values (NULL, 'this', 'is', 'a', 'sample')");
$recID = $sth->{'mysql_insertid'};

$recID now has the AUTO_INCREMENTed value for the record you just inserted.

I hope this answers your question.

NOTE: You probably dont have the dbExecute() function, it just builds the query string and executes it, returning the statement handle... send me an email if you want my database.pl file...

vlet
12-30-01, 10:24 AM
thanks a lot for hel;ping out. I managed to find it somewhere a little bit earlier, and yes - It would probably be a good idea to install mysql on my sys :)

funny though - I'm wondering if different versions, or different platforms have different versions of the DBI installed. While trying to find and example that worked, I ran across many that claimed to work, but just didn't. I doubt these people were just trying to be mean :)