facebook twitter hatena line email

Perl/mysql接続サンプル

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
#!/usr/bin/perl

use strict;
use DBI;

use Data::Dumper;
my ($dbh, $sth);
my ($data_source, $user_name, $user_pass, $sql);
my ($ary);
my (@arr);
print "content-type: text/html\n\n";
$data_source = 'DBI:mysql:test:localhost';  # mysql testDB
$user_name = 'root';
$user_pass = 'pass';
$sql = 'select * from t_test;';
$dbh = DBI->connect($data_source, $user_name, $user_pass) || die $dbh->errstr;

# $ary = $dbh->selectall_arrayref($sql) || die $dbh->errstr;

@arr = &dbselect($dbh, $sql);

print Dumper(@arr);
foreach (@arr) {
  print $_->{id};
  print $_->{name};
  #print Dumper($_);
}
$dbh->disconnect();

sub dbselect {
    my ($conn, $sql) = @_;
    our @data = ();
    
    if (!$conn) {return 0;}
    my $sth = $conn->prepare($sql) || die $conn->errstr;
    my $row;
    if (!$sth->execute) {return 0;}
    if ($sql !~ /^select */) {return 1;}

    while ($row = $sth->fetchrow_hashref) {
    
        push(@data,\%{$row});
    }
    return @data;
}