Skip to content

Instantly share code, notes, and snippets.

@rjattrill
Created June 4, 2012 05:40
Show Gist options
  • Save rjattrill/2866552 to your computer and use it in GitHub Desktop.
Save rjattrill/2866552 to your computer and use it in GitHub Desktop.
Getting last_insert_id with MSSQL and DBIx::DataModel
use Moose;
use DBIx::DataModel;
use DBI;
our $dbh;
our $schema;
sub BUILD {
$dbh = get_dbh();
my %dbh_options;
$dbh_options{last_insert_id} = \&get_last_insert_id;
AppGen::Schema->dbh($dbh, %dbh_options);
$schema = AppGen::Schema->singleton();
}
sub get_dbh {
my $dbi_dsn = 'dbi:ODBC:Driver={SQL Server Native Client 10.0};Server=localhost,1433;Database=app_gen;';
my $user = 'app_gen';
my $password = 'app_gen';
my $dbh = DBI->connect($dbi_dsn, $user, $password);
$dbh->{RaiseError} = 1; # Required for DBIx::DataModel
return $dbh;
}
sub get_last_insert_id() {
my ($dbh, $table, $col) = @_;
my $sql = 'SELECT @@IDENTITY';
my @row_ary = $dbh->selectrow_array($sql);
my $id = $row_ary[0];
return $id;
}
sub save($entity) {
my $table_name = 'Foo';
my $table = $schema->table($table_name);
my $id = $table->insert({FOO => $entity->{FOO}, FOO_REF => $entity->{FOO_REF}});
print "Inserted ID: $id\n";
}
@rjattrill
Copy link
Author

Describes how to get last_insert_id using DBIx::DataModel, DBD::ODBC and MSSQL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment