1

我正在尝试使用单个查询将多个值插入到同一字段中。下面的代码有错误吗?

my $dbh =  DBI->connect("DBI:mysql:accounting:localhost", 'username', 'password',
      {RaiseError => 1});
my @id = [1,18,976,90];
my @name = ['ss','dc','ws','rd'];
my @data = ([@id],[@name]);
my $ab = $dbh->prepare("insert into table (id,name) values (?,?)";);
for my $datam (@data) {
  $ab->execute(@$datam);
}
$ab->finish();

我收到以下错误:DBI::st=HASH(0*a16f774)对于准备语句。这可能是什么原因造成的?

4

2 回答 2

6

由于您实际上没有给出错误,因此无法真正回答您的问题,但我发现您的代码存在问题。你正在做的

$ab->execute([1,18,976,90]);
$ab->execute(['ss','dc','ws','rd']);

当你明显想做的时候

$ab->execute(  1, 'ss');
$ab->execute( 18, 'dc');
$ab->execute(976, 'ws');
$ab->execute( 90, 'rd');

使固定:

my @id = (1,18,976,90);
my @name = ('ss','dc','ws','rd');

for my $i (0..$#id) {
   $ab->execute($id[$i], $name[$i]);
}
于 2012-09-18T05:15:38.213 回答
3

我注意到你的结构:

my @id = [1, 18, 976, 90];

是具有一个元素的数组,即数组引用。您可以按模块检查变量的结构Data::Dumper。所以你只需要简单的数组:

my @id = (1, 18, 976, 90);

使用数据::Dumper

use Data::Dumper;
print Dumper( \@id );

$VAR1 = [
      [
        1,
        18,
        976,
        90
      ]
    ];

解决方案

use List::MoreUtils qw(each_array);

my @id   = (1, 18, 976, 90);
my @name = ('ss', 'dc', 'ws', 'rd');

my $data = each_array(@id, @name);

...
while (my ($id, $name) = $data->()) {

    $ab->execute($id, $name);
}   
于 2012-09-18T05:18:16.027 回答