使用占位符在 Perl 中添加 mysql 值

发布于 2025-01-06 02:29:33 字数 831 浏览 0 评论 0原文

我想向数据库中已有的 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);

上面的代码确实有效,但是如果可能的话,我想减少程序与数据库的连接数量。

谢谢

I want to add a value to a mysql value already present in the database. I know that you can do this by:

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

However, I want the '+10' to be a placeholder, as the value will vary depending upon which iteration of a for loop the program is in. I have written the following, however it does not work:

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

$sth1->execute($ParentTally);

Is it possible to use a placeholder here? I had alternatively written:

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);

The above code does work, however I want to reduce the number of connections my program has to the database if possible.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

庆幸我还是我 2025-01-13 02:29:33

您可以在执行查询之前使用 bind_param 传递值:

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

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

或者,只需将 $int 传递给 execute

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

You could pass the value using bind_param prior to query execution:

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

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

Alternatively, just pass $int to execute :

$sth->execute( $_ ) for 1 .. 10 ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文