我想在添加条目到数据库之前添加功能请求确认,并且还想检查数据库中是否存在该迭代然后它应该抛出警告消息。我的代码是:
my $dbh = DBI->connect(
"dbi:mysql:dbname=agilefant-test",
"agilefant-test",
"Agilefant-test",
{ RaiseError => 1 },
) or die $DBI::errstr;
foreach $iter (keys(%iterations)) {
my $req = "INSERT into backlogs (backlogtype, name, startDate, endDate, parent_id) VALUES ('Iteration', '$iter', '" .
$iterations{ $iter }->{start} . " 08:00', '" .
$iterations{ $iter }->{end} . " 18:00', '" .
$project . "');" ;
print $req . "\n";
my $sth = $dbh->prepare("INSERT into backlogs (backlogtype, name, startDate, endDate, parent_id) VALUES ('Iteration', '$iter', '" .
$iterations{ $iter }->{start} . " 08:00', '" .
$iterations{ $iter }->{end} . " 18:00', '" .
$project . "');");
$sth->execute() or die $DBI::errstr;
$sth->finish();
}
答案 0 :(得分:0)
我不确定我是否理解你的问题。
要求确认:我会做类似
的事情print "insert iteration $iter?";
$yesno=<>;
if (substr($yesno, 0, 1) eq "y") {
.... handle the insert
}
关于警告信息:执行类似
的操作$stmt="select count(1) from backlogs where name='$iter'";
$sth=$dbh->prepare($stmt);
$sth->execute();
($count)=$sth->fetchrow_array();
if ($count>0) {
print "WARNING: $iter already exists.\n";
}
当然,如果你使用绑定变量可以提高效率(并且在你无法查明$ iter的来源的情况下也可以防止sql注入):
# this goes in front of the loop
$stmt="select count(1) from backlogs where name=?";
$sth=$dbh->prepare($stmt);
# this goes inside the loop
$sth->execute($iter);
($count)=$sth->fetchrow_array();
if ($count>0) {
print "WARNING: $iter already exists.\n";
}
如果name列上有唯一索引,您也可以只执行insert语句,然后检查oracle错误ORA-23000,这意味着您只是尝试插入第二行。