【发布时间】:2018-08-25 08:39:16
【问题描述】:
#!/usr/bin/perl
print "content-type:text/html\n\n";
print "<html><body>";
use CGI;
use DBI;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
$db="New";
$user="root";
$password="isRovss*%1u";
$host="localhost";
$dbh=DBI->connect("DBI:mysql:database=$db:$host",$user,$password) ||
die "couldnt open database:$DBI :: errstr";
$sth=$dbh->prepare("select * from stud");
$rv=$sth->execute();
print "<table>";
print "<tr><th>id</th></tr><tr><th>name</th></tr><tr><th>age</th>
</tr>";
while (@row = $sth->fetchrow_array()) {
$id=$row[0];
$name=$row[1];
$age=$row[2];;
}
print "<tr><td>$id</td></tr><tr><td>$name</td></tr><tr><td>$age</td>
</tr>";
print "</table>";
$rc=$sth->finish();
print "Database closed";
print "</body></html>";
我正在尝试使用 Perl 连接 mysql 数据库。我使用的是 Mac OS,它显示“无法连接数据库”。
上面给出了我使用的代码。请帮帮我。
【问题讨论】:
-
那台机器上是否有数据库运行?您可以使用
mysql命令和相同的凭据通过命令行连接到它吗? -
您的代码非常过时。如果你从一本书中得到这个,请使用更现代的书。它教你过时的东西。您应该首先在代码顶部添加
use strict和use warnings,然后使用my声明变量。 -
感谢您的意见,@simbabque。我没有任何编码经验,所以我从互联网上关注了这个。我会尝试使用严格和警告命令。
-
在the Perl tag wiki here on Stack Overflow 中有很多学习现代 Perl 的好资源。看看那些,忘记你现在正在做的教程。你现在让你的生活变得艰难。 :)