Perl 之 DBI 执行 SQL 查询并读取结果

use DBI;
my $driver="DBI:mysql";
my $database="sample_db";
my $user="root";
my $host="localhost";

my $dbh = DBI->connect("$driver:database=$database;host=$host;user=$user")
    or die "Can't connect: " . DBI->errstr;
my $sth=$dbh->prepare("SELECT name FROM Employee") 
    or die "Can't prepare sql statement" . DBI->errstr;

$sth->execute() or die "Can't prepare sql statement". $sth->errstr;
my($name);
$sth->bind_columns(\$name);
printf"\t%-20s%\n","Name"
while( $sth->fetch()){
     printf "   %-25s\n",$name;
}

$sth->finish();
$dbh->disconnect();

编程技巧