use strict; use warnings; use DBI; use Carp qw( confess croak ); my $dbh = DBI->connect( "DBI:mysql:db=test1001;host=localhost", "pm", "correcthorsebatterystaple", { RaiseError => 1, AutoCommit => 0, PrintError => 0, # do our own error handling. } ) or die "DB connect: $DBI::errstr"; eval { $dbh->do(q[ INSERT INTO ref(color) VALUES (?) ], undef, 'blue'); my $last_ref = $dbh->last_insert_id('','','',''); printf STDERR "last ref: %s\n", $last_ref; $dbh->do(q[ INSERT INTO t1(ref_id) VALUES (?) ], undef, $last_ref); my $last_t1 = $dbh->last_insert_id('','','',''); printf STDERR "last t1: %s\n", $last_t1; $dbh->commit; }; if ($@) { my $err = $@; # save $@, as rolling back below could also fail. # attempt to rollback, which could also fail. eval { $dbh->rollback; } if ($dbh); confess( "DB error: $err" ); } __END__ Schema used for the test1001 DB is as follows: CREATE DATABASE test1001; use test1001; GRANT ALL ON test1001.* TO pm; CREATE TABLE ref( id BIGINT PRIMARY KEY AUTO_INCREMENT, color TEXT ); CREATE TABLE t1( id BIGINT PRIMARY KEY AUTO_INCREMENT, ref_id BIGINT REFERENCES ref(id) ON DELETE CASCADE ON UPDATE CASCADE );