SQL-Easy
view release on metacpan or search on metacpan
lib/SQL/Easy.pm view on Meta::CPAN
return $sth->{mysql_insertid};
}
sub execute {
my ($self, $sql, @bind_variables) = @_;
$self->_reconnect_if_needed();
my $sth = $self->{dbh}->prepare($sql);
$self->_run_cb_before_execute($sql, @bind_variables);
$sth->execute(@bind_variables) or croak $self->{dbh}->errstr;
return 1;
}
sub _run_cb_before_execute {
my ($self, $sql, @bind_variables) = @_;
if (defined $self->{_cb_before_execute}) {
$self->{_cb_before_execute}->(
sql => $sql,
bind_variables => \@bind_variables,
);
}
return '';
}
sub _reconnect_if_needed {
my ($self) = @_;
if (time - $self->{last_connection_check} > $self->{connection_check_threshold}) {
if (_check_connection($self->{dbh})) {
$self->{last_connection_check} = time;
} else {
$self->{dbh}= _get_connection($self->{settings});
}
}
}
sub _get_connection {
my ($self) = @_;
my $dsn = "DBI:mysql:database=" . $self->{db}
. ";host=" . $self->{host}
. ";port=" . $self->{port};
my $dbh = DBI->connect(
$dsn,
$self->{user},
$self->{password},
{
PrintError => 0,
RaiseError => 1,
mysql_auto_reconnect => 0,
mysql_enable_utf8 => 1,
},
) or croak "Can't connect to database. Error: " . $DBI::errstr . " . Stopped";
return $dbh;
}
sub _check_connection {
my $dbh = shift;
return unless $dbh;
if (my $result = $dbh->ping) {
if (int($result)) {
# DB driver itself claims all is OK, trust it:
return 1;
} else {
# It was "0 but true", meaning the default DBI ping implementation
# Implement our own basic check, by performing a real simple
# query.
my $ok;
eval {
$ok = $dbh->do('select 1');
};
return $ok;
}
} else {
return;
}
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
SQL::Easy - extremely easy access to sql data
=head1 VERSION
version 2.0.0
=head1 SYNOPSIS
Let image we have db 'blog' with one table:
CREATE TABLE `posts` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dt` datetime NOT NULL,
`title` VARCHAR(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert INTO `posts` (`dt`, `title`) values
('1', '2010-07-14 18:30:31', 'Hello, World!'),
('2', '2010-08-02 17:13:35', 'use perl or die')
( run in 0.595 second using v1.01-cache-2.11-cpan-d7f47b0818f )