我正在尝试使用单个查询将多个值插入到同一字段中。以下代码是否有任何错误?
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)
用于准备语句。可能导致这种情况的原因是什么?
答案 0 :(得分: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]);
}
答案 1 :(得分:3)
我注意到你的结构:
my @id = [1, 18, 976, 90];
是包含一个元素的数组,即数组引用。您可以按模块Data::Dumper
检查变量的结构。所以你只需要简单的数组:
my @id = (1, 18, 976, 90);
使用Data :: 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);
}