无法使用 perl DBI 模块连接到 mysql



嗨,我正在尝试使用以下perl脚本连接到mysql数据库:

#!/usr/bin/perl -w
use strict;
use DBI;
my $dbh = DBI->connect(          
"dbi:mysql:dbname=MYDATABASENAME", 
"MYUSERNAME",                          
"MYPASSWORD",                          
{ RaiseError => 1 },         
) or die $DBI::errstr;
my $sth = $dbh->prepare( "SELECT * FROM classes" );  
$sth->execute();
my ($class_id, $class_name, $class_number) = $sth->fetchrow();
print "$class_id $class_name $class_numbern";
my $fields = $sth->{NUM_OF_FIELDS};
print "We have selected $fields field(s)n";
my $rows = $sth->rows();
print "We have selected $rows row(s)n";
$sth->finish();
$dbh->disconnect();

现在我只是得到一个空白屏幕,我不知道为什么我至少没有收到错误消息。我花了20多个小时试图弄清楚这一点,这就是为什么我希望有人能看到我做错了什么。提前谢谢。

在评论中,您添加了本应真正出现在原始问题中的有用信息。

抱歉,我没有从命令行运行它。我已将其保存在我的虚拟主机帐户的cgi-bin文件夹中。运行脚本时,浏览器中出现空白屏幕。

此程序不会作为 CGI 程序工作,因为您不会返回内容类型标头。尝试将这两行添加到程序的顶部。

use CGI 'header';
print header('text/plain');

您还应该找出 Web 服务器错误日志所在的位置并检查其中是否存在错误。CGI程序不会将其错误发送到浏览器是一项安全功能(尽管我希望看到一些迹象表明存在问题)。

同样值得指出的是,use warnings编译指示是在 5.6 版本(2000 年发布)中添加到 Perl 中的,并且大多数程序员使用它来代替 shebang 行上的-w

我还建议,在编写CGI版本之前,通常(可能总是)将新的Perl模块作为命令行程序进行测试是一个好主意。CGI只是在你学习新东西时增加了额外的、不必要的复杂性。

这应该有效。如果在本地运行脚本,则该port是可选的。

use strict;
use warnings;
use DBI;
my $database   = 'name_of_database';
my $DBhost     = 'localhost';
my $port       = 'portnumber';
my $username   = 'user123';
my $password   = 'password123';
my $dbh = DBI->connect("dbi:mysql:database=$database;host=$DBhost;port=$port",$username,$password,                          
{  RaiseError       => 1,
PrintError       => 0,
AutoCommit       => 1,
FetchHashKeyName => 'NAME_lc'}, ) or die $DBI::errstr;
my $sth = $dbh->prepare( "SELECT * FROM classes" );  
$sth->execute();
my ($class_id, $class_name, $class_number) = $sth->fetchrow();
print "$class_id $class_name $class_numbern";
my $fields = $sth->{NUM_OF_FIELDS};
print "We have selected $fields field(s)n";
my $rows = $sth->rows();
print "We have selected $rows row(s)n";
$sth->finish();
$dbh->disconnect();

最新更新