package Tie::DBI;
use 5.008003;
use strict;
use warnings;
use base 'Tie::Scalar';
use DBI;
our $VERSION = '0.01';
sub TIESCALAR {
my $class = shift;
my ($dsn, $user, $pass) = @_;
my $self = {
dbh => undef,
};
$self->{dbh} = DBI->connect($dsn, $user, $pass);
bless $self, $class;
}
sub STORE {
my ($self, $value) = @_;
if ( $self->{sth} && ref($value) eq 'ARRAY' ) {
$self->{sth}->execute(@$value);
} else {
$self->{sth} = $self->{dbh}->prepare($value);
if ( $self->{sth}->FETCH('NUM_OF_PARAMS') == 0 ) {
$self->{sth}->execute();
}
}
}
sub FETCH {
my ($self) = @_;
return undef if !$self->{sth} || $self->{dbh}->err;
return $self->{sth}->fetchrow_arrayref() || 0;
}
1;
####
my $dbh;
tie $dbh, 'Tie::DBI', $dsn, $user, $pass;
$dbh = "select * from table where field = $value";
while ( my $row = $dbh ) {
print $row->[0], "\n";
}
####
$dbh = "select * from table where field = ?";
$dbh = [$value];
while ( my $row = $dbh ) {
print $row->[0], "\n";
}