6

如何从 Perl 调用 MySQL 存储过程?存储过程功能对 MySQL 来说是相当新的,Perl 的 MySQL 模块似乎还没有赶上。

4

5 回答 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。

于 2008-09-15T17:01:51.913 回答
5

在 DBD::mysql 文档中的多个结果集部分中有一个示例。

于 2008-09-15T16:27:46.223 回答
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";
}

我希望它有所帮助。

于 2012-05-02T00:35:37.380 回答
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 上查找确切的语法。

于 2008-09-15T16:09:15.037 回答
1

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

   使用 DBI;
   #START:设置数据库并连接
   我的 $host = '*[服务器]*\\*[数据库]*';
   我的 $database = '*[table]*';
   我的 $user = '*[user]*';
   我的 $auth = '*[密码]*';

   我的 $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database";
   我的 $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });

   #END : 设置数据库并连接
   $sql = "exec *[存储过程名称]* *[param1]*,*[param2]*,*[param3]*;";
   $sth = $dbh->prepare($sql);
   $sth->execute or die "SQL 错误: $DBI::errstr\n";
于 2015-03-24T15:59:40.233 回答