6 mysql perl stored-procedures
如何从Perl调用MySQL存储过程?存储过程功能对于MySQL来说是相当新的,而Perl的MySQL模块似乎还没有赶上.
生成数据集的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)'
Run Code Online (Sandbox Code Playgroud)
但是如果你的DBD :: mysql版本太旧了,你得到的结果如下:
DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1.
Run Code Online (Sandbox Code Playgroud)
您可以使用CPAN安装最新的DBD.
首先,您应该通过 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();
Run Code Online (Sandbox Code Playgroud)
请注意,我还没有对此进行测试,您必须在 CPAN 上查找确切的语法。