更新时间:2023-02-02 22:11:32
您已经有了解释和解决方法,但我建议进行以下更改
You already have an explanation and a fix, but I suggest the following changes
您应该prepare
INSERT INTO
SQL语句,然后在循环内execute
. 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\n";
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\n};
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\n};
print qq{Level row2 "size" gives: $size\n};
$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