6

我需要能够通过 DBI 发出“创建触发器”。我似乎无法让分隔符命令正常工作。任何人都可以找到一种方法来完成这项工作吗?

代码:

use strict;
use DBI;
my $dbargs = {mysql_auto_reconnect => 1,
              AutoCommit           => 0,
              RaiseError           => 1,
              ShowErrorStatement   => 1}; 

my $dsn = "DBI:mysql:database=xdisp;host=cycldev06";
my $dbh = DBI->connect( $dsn, 'sqluser', '', $dbargs);

my $sql = qq{ 
    DELIMITER // 
        CREATE TRIGGER `hardware_last_status` BEFORE UPDATE
            ON `hardware` FOR EACH ROW BEGIN
                                IF NEW.status != OLD.status AND NEW.last_status = OLD.last_status THEN
                                    SET NEW.last_status = OLD.status;
                                END IF;
                            END
            //
};

$dbh->do($sql);

结果:

DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER // 
        CREATE TRIGGER `hardware_last_status` BEFORE UPDATE
      ' at line 1 at test.pl line 24.

并且该 SQL 在 MySQL 命令行上运行良好。

4

1 回答 1

7

客户端程序使用该delimiter命令来确定 SQL 语句的限制。服务器本身看不到它(几乎可以肯定)。因此,在 Perl + DBI 中,您应该简单地省略分隔符。因此,您应该执行的命令是:

my $sql = qq{ 
    CREATE TRIGGER `hardware_last_status` BEFORE UPDATE
        ON `hardware` FOR EACH ROW BEGIN
                            IF NEW.status != OLD.status AND NEW.last_status = OLD.last_status THEN
                                SET NEW.last_status = OLD.status;
                            END IF;
                        END
};
于 2012-09-14T02:03:17.727 回答