一个从xml文件向mysql数据库里倒数据的perl程序


#!/usr/bin/perl

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");
}
}

Discussion Area - Leave a Comment




*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word