全部博文(1144)
分类: LINUX
2009-12-09 18:26:15
use strict;
use DBI;
use XML::Parser;
# create hash to hold values for expected column names
my %row = (
"key" => undef,
"name" => undef);
# connect to database and create parser object
my $dbh = DBI->connect ("DBI:mysql:ipmap",
"root", "passwd",
{ RaiseError => 1, PrintError => 0});
my $parser = new XML::Parser (
Handlers => {
Start => \&handle_start,
End => \&handle_end,
Char => \&handle_text
}
);
# parse file and disconnect
$parser->parsefile ("example.xml");
$dbh->disconnect ();
sub handle_start
{
my ($p, $tag) = @_; # parser, tag name
if ($tag eq "row")
{
foreach my $key (keys (%row))
{
$row{$key} = undef;
}
}
}
sub handle_text
{
my ($p, $data) = @_; # parser, text
my $tag = $p->current_element ();
$row{$tag} .= $data if exists ($row{$tag});
}
sub handle_end
{
my ($p, $tag) = @_; # parser, tag name
if ($tag eq "row")
{
my $str;
# construct column assignments for INSERT statement
foreach my $key (keys (%row))
{
$str .= "," if $str;
$str .= "$key=" . $dbh->quote($row{$key});
}
$dbh->do ("INSERT INTO ipmap SET $str");
}
}