【问题标题】:Perl + DBI + MySQL: How To Run Multiple Queries/Statements [duplicate]Perl + DBI + MySQL:如何运行多个查询/语句 [重复]
【发布时间】:2014-05-07 17:14:03
【问题描述】:

目前,我在 MYSQL 上运行多个语句,如下所示;

my $sth1 = $dbh->prepare("ALTER TABLE whatever....");
my $sth2 = $dbh->prepare("UPDATE whatever....");
my $sth3 = $dbh->prepare("ALTER TABLE whatever....");
my $sth4 = $dbh->prepare("DROP TABLE whatever....");
my $sth5 = $dbh->prepare("DROP TABLE whatever....");


$sth1->execute;
$sth1->finish;
$sth2->execute;
$sth2->finish;
$sth3->execute;
$sth3->finish;
$sth4->execute;
$sth4->finish;
$sth5->execute;
$sth5->finish;

此代码运行良好。

但是,我有大约 50 多个这样的查询。所以你可以想象上述线条的大小。我在上面粘贴的只是 5 个查询。

问题:

有没有更好的优雅方式使用 Perl DBI 运行多个 MySQL 查询/语句?

【问题讨论】:

  • 将你的 sql 查询放入数组并运行 foreach?
  • @mpapec,我最终得到了你的建议,我的脚本现在要小得多。不幸的是,您将其添加为评论,而米勒将其添加为答案。因此我接受了这个答案。你们俩都建议了相同的解决方案,这对我的用例非常有用。谢谢。

标签: mysql perl dbi


【解决方案1】:

至少,您应该只迭代您的 sql 字符串。将or die 添加到您的execute 方法中也是一个好主意:

my @sql = (
    q{ALTER TABLE whatever....},
    q{UPDATE whatever....},
    q{ALTER TABLE whatever....},
    q{DROP TABLE whatever....},
    q{DROP TABLE whatever....},
);

for (@sql) {
    my $sth = $dbh->prepare($_);
    $sth->execute or die $dbh->errstr;
}

【讨论】:

  • 或者只是将 RaiseError 设置为 true 并且任何错误都会消失。
  • @Miller。谢谢。我的脚本现在看起来更整洁了。
  • 请注意,您不应该在该循环中使用 $sth->finish 行。见metacpan.org/pod/DBI#finish
【解决方案2】:

DBD::mysql 有一个参数 mysql_multi_statements:

从 MySQL 4.1 开始,可以使用此选项启用对由分号 (;) 分隔的多个语句的支持。如果还启用了服务器端预处理语句,则启用此选项可能会导致问题。

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 2016-05-26
    • 2014-01-28
    • 1970-01-01
    • 2011-10-06
    • 2010-11-21
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    相关资源
    最近更新 更多