Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Writing DB Module using MethodMaker - Some More methods Added..

by vishi83 (Pilgrim)
on Oct 20, 2005 at 14:46 UTC ( [id://501682]=sourcecode: print w/replies, xml ) Need Help??
Category: Object Oriented Perl
Author/Contact Info Vishi Chennai,India
Description: This code is intended for beginners who want to try simple DBI script in Object Oriented Style using MethodMaker. You can create your own methods like connect(), save(), delete() etc as i hav done in my code.. ThankYou.

MakerDB.pm

  package MakerDB;

  use strict;
  use warnings;
  use Carp;
  use DBI;  
  use Data::Dumper;
 
  my $dbh;
  my $sth;
  


  my $name,
  my $pass;
  use Class::MethodMaker
   get_set => [ { -read_cb => sub  {
                my $self = shift;
            my $dsn = 'DBI:mysql:mydb';
            my $dbuser ='root';
            my $dbpass = '';    
            eval {
                        $dbh=DBI->connect($dsn,
                         $dbuser,
                         $dbpass,
                         { RaiseError => 1,
                          AutoCommit => 0 }
                                       ); 
                             };
                      croak "\n\ncould not connect : $@" if $@;
                           return $dbh;
                            } 
         },'connect',
        
             {  -read_cb => sub {
            
            print "Enter Name : ";
            chomp($name = <STDIN>);
            print "Enter Password : ";
            chomp($pass = <STDIN>);

            my $self = shift;
            my $query = qq{INSERT INTO userlog VALUES(?,?)};
            eval {
                    $sth = $dbh->prepare($query);
                $sth->execute($name,$pass);
                 };
                croak "\n\nCheck the Query..Data cannot be inserted : 
+$@" if $@;
                return $sth;
                                    }
                 },'save',
    
         {  -read_cb => sub {
            my $self = shift;
                print "Enter the Name of the Record to be Deleted :\t"
+;
             chomp($name = <STDIN>);
             my $query = qq[DELETE FROM userlog WHERE NAME = '$name'];
            eval {
                    $sth = $dbh->do($query);
                 };
                croak "\n\nDelete Query Failed : $@" if $@;
                return $sth;                
                    }
        },'delete'     
        ],                                    
    new  => 'new';
  1;
This will be your .pl file ...
 
  use package MakerDB;
  use strict;
  my $newObj;
  my $dbh;
  my $sth;
 

   $newObj = MakerDB->new();
   print "\n\tSuccessfully connected to DB\n\n" if $dbh=$newObj->conne
+ct();
  
# Insert a record 
   print "\nData Insertion Sucessful\n" if $newObj->save();

   $sth=$dbh->prepare("SELECT NAME, PASSWORD FROM userlog");
   $sth->execute();
   
   my $href;
   while ($href=$sth->fetchrow_hashref())  {
      print "\n";
     print Dumper $href;
  }
 
    # Delete a record 
      $newObj->delete();
Replies are listed 'Best First'.
Re: Writing DB Module using MethodMaker
by jesuashok (Curate) on Oct 24, 2005 at 06:02 UTC
    Hi vishi,
    To have more clear understanding for the people who is reading your sample code I wouild like to add some more additional information on the same :-

    Hi newbies

    Create a file called "MakerDB.pm" by using your favourite editor.

    then have the following contents
    package MakerDB; use strict; use warnings; use Carp; use DBI; use Data::Dumper; my $dbh; my $dbobj; use Class::MethodMaker get_set => [ { -read_cb => sub { my $self = shift; my $dsn = 'DBI:mysql:mydb'; my $dbuser ='root'; my $dbpass = ''; eval { $dbh=DBI->connect($dsn, $dbuser, $dbpass, { RaiseError => 1, AutoCommit => 0 } ); }; croak "\n\ncould not connect : $@" if $@; return $dbh; } },'connect' ], new => 'new'; 1;
    The last line should contain "1;" that is the successful return value from package ( that is missed out from the sample given by Vishi )

    Then create any perl file to make use of the module "MakerDb"


    The perl file contains the following:-
    use strict; my $vObj = MakerDB->new(); print "\n\tSuccessfully connected to DB\n\n" if my $dbhandle=$vObj- +>connect(); my $sth=$dbhandle->prepare("SELECT NAME, PASSWORD FROM userlog"); $sth->execute(); my $href; while ($href=$sth->fetchrow_hashref()) { print "\n"; print Dumper $href; }

    If you create those two files and run that will work fine as expected. this will be helpful for all the newbies who are all new to Perl also.


    thanx.

    "Keep pouring your ideas"

    2005-10-24 jdporter edited: added code and br tags

      I have updated my MakerDB.pm .. methods like save and delete added..

      I leave the rest to your logic and you can build it further using your own ideas..

      ThankYou, vishi

A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://501682]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-19 05:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found