如何从Perl调用MySQL存储过程?

6

我该如何从Perl中调用MySQL存储过程?存储过程功能对于MySQL来说还是比较新的,而且Perl的MySQL模块似乎还没有跟上。

5个回答

7

MySQL存储过程需要使用Perl DBD::mysql 4.001或更高版本来生成数据集。(http://www.perlmonks.org/?node_id=609098

下面是一个在更新的版本中可以工作的测试程序:

mysql> delimiter //
mysql> create procedure Foo(x int)
  -> begin
  ->   select x*2;
  -> end
  -> //

perl -e 'use DBI; DBI->connect("dbi:mysql:database=bonk", "root", "")->prepare("call Foo(?)")->execute(21)'

但是如果你使用的是过于老旧的DBD::mysql版本,你将会得到以下结果:

DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1.

您可以使用CPAN安装最新的DBD。


5

在DBD::mysql文档中的多结果集部分有一个示例,请查看


3
#!/usr/bin/perl
# Stored Proc - Multiple Values In, Multiple Out
use strict;
use Data::Dumper;
use DBI;
my $dbh = DBI->connect('DBI:mysql:RTPC;host=db.server.com',
    'user','password',{ RaiseError => 1 }) || die "$!\n";
my $sth = $dbh->prepare('CALL storedProcedure(?,?,?,?,@a,@b);');
$sth->bind_param(1, 2);
$sth->bind_param(2, 1003);
$sth->bind_param(3, 5000);
$sth->bind_param(4, 100);
$sth->execute();
my $response = $sth->fetchrow_hashref();
print Dumper $response . "\n";

我花了一些时间才搞清楚,但是通过上面的操作,我得到了我所需要的结果。如果你需要获取多行返回值,我猜你只需要...

while(my $response = $sth->fetchrow_hashref()) {
    print Dumper $response . "\n";
}

希望这有所帮助。


2

首先,您应该使用DBI库进行连接,然后使用绑定变量。例如:

#!/usr/bin/perl
#
use strict;
use DBI qw(:sql_types);

my $dbh = DBI->connect(
            $ConnStr,
            $User,
            $Password,
            {RaiseError => 1, AutoCommit => 0}
          ) || die "Database connection not made: $DBI::errstr";
my $sql = qq {CALL someProcedure(1);}    } 

my $sth = $dbh->prepare($sql);
eval {
  $sth->bind_param(1, $argument, SQL_VARCHAR);
};
if ($@) {
 warn "Database error: $DBI::errstr\n";
 $dbh->rollback(); #just die if rollback is failing
}

$dbh->commit();

请注意,我还没有测试过这个,你需要在CPAN上查找确切的语法。

你在 eval {} 后面忘记加分号了。这是一个常见的错误。 - Leon Timmermans

1

您好,类似于上面的示例,但使用SQL exec。我无法使CALL命令正常工作。您需要填写方括号中的任何内容并删除方括号。

   use DBI;
   #START: 设置数据库并连接
   my $host     = '*[服务器]*\\*[数据库]*';
   my $database = '*[表]*';
   my $user     = '*[用户]*';
   my $auth     = '*[密码]*';
my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database"; my $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });
#END : 设置数据库并连接 $sql = "exec *[存储过程名称]* *[参数1]*,*[参数2]*,*[参数3]*;"; $sth = $dbh->prepare($sql); $sth->execute or die "SQL Error: $DBI::errstr\n";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接