DBD :: mysql fetchrow_array失败:fetch()没有execute()?

时间:2013-09-15 19:49:49

标签: mysql windows perl apache cgi

我收到以下代码的错误:

#!C:/usr/bin/perl -w

use CGI;
use strict;
use DBI();
use CGI::Carp qw(fatalsToBrowser);


print "content-type: text/html; charset=iso-8859-1\n\n";

my $q=new CGI;
my $ename=$q->param('ename');
my $email=$q->param('email');

print $q->header;
print "<br>$ename<br>";


#connect to database.
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost","root","mukesh",
          {'RaiseError' => 1});

eval {$dbh->do("CREATE TABLE IF NOT EXISTS emp (ename VARCHAR(20), email VARCHAR(50))")};
print "<br>creating table emp failed: $@<br>" if $@;


my $sql="INSERT INTO emp(ename,email) values('$ename','$email')";

my $sth = $dbh->prepare($sql) or die "Can't prepare $sql:$dbh->errstrn";
#pass sql query to database handle


my $rv = $sth->execute() or die "can't execute the query: $sth->errstrn";

my @row;
while (@row = $sth->fetchrow_array) {
print join(", ",@row);
}

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

if ($rv==1){
print "<br>Record has been successfully updated !!!<br>";
}else{
print "<br>Error!!while inserting record<br>";
exit;
}

请建议。问题是什么。 如果我删除这段代码,它工作正常。

my @row;
while (@row = $sth->fetchrow_array) {
print join(", ",@row);
}

1 个答案:

答案 0 :(得分:4)

您尝试在DBI中使用常见的SELECT周期 - 准备,执行,获取 - 用于non-select查询(在您的情况下为INSERT)。您可能应该做的是直接检查execute的结果。引用the doc

  

对于非SELECT语句,execute返回行数   受影响的,如果知道。如果没有行受影响,则执行返回   &#34; 0E0&#34;,Perl将其视为0但将视为真。注意   没有行受语句影响不是错误。如果   受影响的行数未知,则execute返回-1。