Database Reference
In-Depth Information
Using API-specific methods to obtain AUTO_INCREMENT values
LAST_INSERT_ID()
is an SQL function, so you can use it from within any client that can
execute SQL statements. On the other hand, you do have to execute a separate statement
to get its value. When you write your own programs, you may have another choice.
Many MySQL interfaces include an API-specific extension that returns the
AUTO_IN
CREMENT
value without executing an additional statement. Most of our APIs have this
capability.
Perl
Use the
mysql_insertid
attribute to obtain the
AUTO_INCREMENT
value generated
by a statement. This attribute is accessed through either a database handle or a
statement handle, depending on how you issue the statement. The following ex‐
ample references it through the database handle:
$dbh
->
do
(
"INSERT INTO insect (name,date,origin)
VALUES('moth','2014-09-14','windowsill')"
);
my
$seq
=
$dbh
->
{
mysql_insertid
};
To access
mysql_insertid
as a statement-handle attribute, use
prepare()
and
execute()
:
my
$sth
=
$dbh
->
prepare
(
"INSERT INTO insect (name,date,origin)
VALUES('moth','2014-09-14','windowsill')"
);
$sth
->
execute
();
my
$seq
=
$sth
->
{
mysql_insertid
};
Ruby
The Ruby DBI driver for MySQL exposes the client-side
AUTO_INCREMENT
value
using the
func
database-handle method that returns driver-specific values:
dbh
.
do
(
"INSERT INTO insect (name,date,origin)
VALUES('moth','2014-09-14','windowsill')"
)
seq
=
dbh
.
func
(
:insert_id
)
PHP
The PDO interface for MySQL has a
lastInsertId()
database-handle method that
returns the most recent
AUTO_INCREMENT
value:
$dbh
->
exec
(
"INSERT INTO insect (name,date,origin)
VALUES('moth','2014-09-14','windowsill')"
);
$seq
=
$dbh
->
lastInsertId
();
Python
The Connector/Python driver for DB API provides a
lastrowid
cursor object at‐
tribute that returns the most recent
AUTO_INCREMENT
value:
cursor
=
conn
.
cursor
()
cursor
.
execute
(
'''
INSERT INTO insect (name,date,origin)
VALUES('moth','2014-09-14','windowsill')