1. Home
  2. Computing & Technology
  3. Perl

Adding Object-Relational Mapping to your Perl Application - Part Three
Adding New Records to the Database

by Kirk Brown
for About.com

Now that we've seen how to look up existing records in our database, lets take a quick look at how simple it is to add new contacts.
use MyApp::Contact;

$u = MyApp::Contact->new(name => 'Moe', email => 'moe@thestooges.com');
$u->save;

$moe = MyApp::Contact->new(email => 'moe@thestooges.com'); $moe->load; print "User's name is ".$moe->name.", email address is ".$moe->email.", database id is ".$moe->id.".\n";
Basically what we're doing is using the new() method to build our contact manually by putting in a hash with the email address and name. Once that's complete, we simply make a quick call to save() and Rose::DB will insert it into the database.
$u = MyApp::Contact->new(name => 'Moe', email => 'moe@thestooges.com');
$u->save;
That should insert the record into the database and MySQL will create an ID for it. Next we try loading the record by it's email address to see if it worked:
$moe = MyApp::Contact->new(email => 'moe@thestooges.com'); $moe->load;
and finally print the record and look at all the values:
print "User's name is ".$moe->name.", email address is ".$moe->email.", database id is ".$moe->id.".\n";
Which of course, should read something like:
User's name is Moe, email address is moe@thestooges.com, database id is 3.\n";

Previous: Using Rose:DB in Your Application

Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Working With Databases
  5. A tutorial on using Rose::DB and Rose::DB::Object to add Object-Relational Mapping to your Perl application.>

©2009 About.com, a part of The New York Times Company.

All rights reserved.