更新时间:2023-02-02 21:57:47
您已经有了解释和修复,但我建议进行以下更改
You already have an explanation and a fix, but I suggest the following changes
您应该准备
INSERT INTO
SQL 语句,然后在循环中执行
它.do
开销更大
You should prepare
the INSERT INTO
SQL statement and then execute
it within the loop. do
has a much bigger overhead
//
( descendant-or-self::node()
) XPath 结构很昂贵,您应该保留它以备不时之需知道元素在文档中的位置,这是非常罕见的.在这种情况下,row1
元素位于 /database/row1s/row1
并且 row2
元素位于 row2s/row2
相对于那个
The //
( descendant-or-self::node()
) XPath construct is expensive and you should reserve it for cases where you have no idea where the element will be within the document, which is very rare. In this case the row1
elements are at /database/row1s/row1
and the row2
elements are at row2s/row2
relative to that
如果你想在带引号的字符串中使用引号字符,使用不同的分隔符会更简洁.例如 "My name is "$name""
比 qq{My name is "$name"}
It is much cleaner to use different delimiters if you want to use quote characters within a quoted string. For instance "My name is "$name""
is much better as qq{My name is "$name"}
这是您的程序的一个版本,可能会有所帮助.
Here's a version of your program that may help.
use strict;
use warnings;
use XML::XPath;
use DBI;
my $xp = XML::XPath->new( filename => 'animals4.xml' );
my $dbh = DBI->connect(
'DBI:mysql:test', 'user', 'pw',
{ RaiseError => 1, PrintError => 0}
) or die "Fehler beim Verbidungsaufbau zum MariaDB-Server: $DBI::err -< $DBI::errstr
";
my $insert_animal = $dbh->prepare('INSERT INTO animal4 (name, category, type, size) VALUES (?, ?, ?, ?)');
for my $row1 ( $xp->findnodes('/database/row1s/row1') ) {
my $name = $row1->getAttribute('name');
my $category = $row1->getAttribute('category');
printf qq{Level --- row1 "name" gives: $name
};
my @row2 = $xp->findnodes('row2s/row2', $row1);
if ( @row2 ) {
for my $row2 ( @row2 ) {
my $type = $row2->getAttribute('type');
my $size = $row2->getAttribute('size');
print qq{Level row2 "type" gives: $type
};
print qq{Level row2 "size" gives: $size
};
$insert_animal->execute($name, $category, $type, $size);
}
}
else {
$insert_animal->execute($name, $category, undef, undef);
}
}
输出
Level --- row1 "name" gives: fox
Level row2 "type" gives: 1
Level row2 "size" gives: 10
Level row2 "type" gives: 2
Level row2 "size" gives: 8
Level --- row1 "name" gives: horse
Level row2 "type" gives: 3
Level row2 "size" gives: 100
Level --- row1 "name" gives: bee
Level --- row1 "name" gives: wasp