1

我在使用 perl 获得简单的 DBI 连接时遇到问题。

我放置了一个位置检查器来查看数据库句柄是否未定义并且它总是未定义。有没有明显的错误?我确信我输入的信息是正确的,因为我在 php 脚本中使用它。

#!/usr/bin/perl -w
use warnings;
print "Content-Type: text/html\n\n";

use DBI;

# Connecting to the database
# Replace DATABASENAME with the name of the database,
# HOSTNAME with the hostname/ip address of the MySQL server.
$drh = DBI->install_driver("mysql");
$dsn =   "DBI:mysql:database=db_name;host=host_name";
$dbh = DBI->connect($dsn,"username","password");
if(defined $dbh)
{
    print "Yes<br />";
}
else
{
    print "No<br />";
 }

 # Select the data and display to the browser

   $sth = $dbh->prepare("SELECT * FROM customer");
   $sth->execute();
   while (my $ref = $sth->fetchrow_hashref()) {
   print "Found a row: id = $ref->{'cid'}";
}

$sth->finish();

# Disconnect from the database.

$dbh->disconnect();
4

1 回答 1

6

connect如果返回 undef,则会发生错误。在那里抛出一些错误处理。它可能会给你一些有用的信息。

$dbh = DBI->connect($dsn, $user, $pw)
   or die "Unable to connect: $DBI::errstr\n";
于 2012-08-23T20:23:54.397 回答