2012-02-16 46 views
0

我想向数据库中已存在的mysql值添加一个值。我知道,你可以这样做:使用占位符在perl中添加mysql值

my $sql1 =qq(UPDATE genotype SET Tally=Tally+10); 

不过,我想“+10”是一个占位符,作为值将取决于其for循环迭代程序在改变我。写如下,但它不起作用:

my $sql1 =qq(UPDATE genotype SET Tally=Tally + ?); 
my $sth1 = $dbh_m-> prepare($sql1); 

$sth1->execute($ParentTally); 

是否有可能在这里使用占位符?我有另外写道:

my $sql5 =qq(SELECT Tally FROM genotype); 
my $sth5 = $dbh_m-> prepare($sql5); 

$sth5->execute(); 
my $newTally; 

while (my $ChosenTally = $sth5 ->fetch){ 
    for my $field (@$ChosenTally){ 
     $newTally=$field; 
    } 
} 

$newTally+=$ParentTally; 


my $sql6 =qq(UPDATE genotype SET Tally= ?); 
my $sth6 = $dbh_m-> prepare($sql6); 

$sth6->execute($newTally); 

上述代码的工作,但是我想减少我的程序有可能的数据库连接的数量。

感谢

回答

0

你可以通过使用以前bind_param查询执行的值:

my $sth = $dbh->prepare($query_with_placeholder); 

for my $int (1 .. 10) { 
    $sth->bind_param(1, $int, SQL_INTEGER); 
    $sth->execute; 
} 

或者,只是通过$intexecute

$sth->execute($_) for 1 .. 10 ; 
+0

谢谢你,但我仍不很不知道如何让它将数字添加到数据库中已存在的值,当我尝试它时,它不会将值添加到已经存在的值中怨恨。 (例如,数据库的值为10,ParentTally为值10,所以我希望数据库中新的总值为20) – Lisa 2012-02-17 10:45:34