| 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 | |
by vishi83 (Pilgrim) on Oct 24, 2005 at 11:27 UTC | |
| A reply falls below the community's threshold of quality. You may see it by logging in. |