Created
October 7, 2011 10:36
-
-
Save chernomyrdin/1269992 to your computer and use it in GitHub Desktop.
Sample perl/mysql code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w -- | |
use warnings; | |
use strict; | |
use utf8; | |
package DoMysql; | |
use DBI; | |
sub connect { | |
my $class = shift; | |
my $self = { | |
dbh => undef, | |
}; | |
$self->{dbh} = DBI->connect( @_ ) or die "Connect error: " . $DBI::errstr; | |
bless $self, $class; | |
} | |
sub DESTROY { | |
my $self = shift; | |
if ($self->{dbh}) { | |
$self->{dbh}->disconnect; | |
undef $self->{dbh}; | |
} | |
} | |
sub do { | |
my $self = shift; | |
my $sth = $self->{dbh}->prepare( shift ) or die "Prepare error: " . $self->{dbh}->errstr; | |
my $code = shift; | |
my $rc = undef; | |
if ($sth->execute) { | |
if ($sth->rows and ref($code) eq 'CODE') { | |
# output field name(s) | |
$code->( join ("\t", @{ $sth->{NAME} }) ); | |
# output results | |
while ( my $row = $sth->fetch ) { | |
$code->( join ("\t", map { $self->{dbh}->quote( $_ ) } @{ $row }) ); | |
} | |
} | |
$sth->finish; | |
} | |
else { | |
die "Execute error: " . $self->{dbh}->errstr; | |
} | |
} | |
package main; | |
eval { | |
DoMysql->connect( | |
"DBI:mysql:database=chanceweb;host=localhost;mysql_init_command_timeout=1", | |
undef, # username | |
undef, # password | |
{ | |
mysql_enable_utf8 => 1, | |
mysql_init_command => 'SET NAMES utf8', | |
RaiseError => 1, | |
AutoCommit => 0 | |
} | |
)->do( | |
join(' ', @ARGV), | |
sub { | |
print @_, "\n"; | |
} | |
); | |
}; | |
if ($@) { | |
die $@; | |
} | |
1; | |
__END__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment