Reputation: 1
#!/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>";
I am trying to connect the mysql database using Perl. I am using a Mac OS and it says "Couldn't connect database".
The code im using is given above. Please help me out.
Upvotes: 0
Views: 186
Reputation: 943547
Look at the DBI documentation
$dbh = DBI->connect($data_source, $username, $password, \%attr) or die $DBI::errstr;
Compare to your code:
$dbh=DBI->connect("DBI:mysql:database=$db:$host",$user,$password) || die "couldnt open database:$DBI :: errstr";
You've put $DBI::errstr
inside a string literal, and added spaces.
This means your error message reporting code is going to try to try report $DBI
(followed by :: errstr
) instead of the variable containing the error.
Fix that and you can find out what is actually wrong:
$dbh=DBI->connect("DBI:mysql:database=$db:$host",$user,$password)
|| die "couldnt open database:" . $DBI::errstr;
Upvotes: 3
Reputation: 69244
Using CGI is an unnecessary distraction here. I recommend that you try writing a non-CGI program that connects to the database first and, when you get that working, you can copy the same connection code into your CGI program.
In fact, even before that, you should ensure that you can use your connection details to connect to the MySQL server using the standard MySQL tools.
What happens if you open a command line window and run the following?:
mysql -h localhost -u root -p -D New
Almost certainly, this is a problem with connecting to the database and has nothing to do with Perl or CGI.
Upvotes: 2