Perl,将2D哈希插入mySQL数据库

时间:2016-05-23 20:18:50

标签: mysql perl hash hashtable

我有一个2D哈希,我必须在mySQL数据库中插入..现在mysql表(报告)中列的名称与

相同
  'vm_uuid'  
  'ip_addr'  
  'name'
  'config_name'
  'PrimaryKey' 
  'ComputeNode'

哈希的数据转储器是:

p Dumper %Final
$VAR1 = 'ZTestName1',
$VAR2 = {          'vm_uuid' => '096a18bd-5955-465f-9bd4-d6bd038a4a56|',
          'ip_addr' => '107.250.172.198|172.26.3.8|',
          'name' => 'tap6f684e07-7a|tapa19310a9-7a|',
          'config_name' => 'TestValue',
          'PrimaryKey' => 'TestName',
          'ComputeNode' => 'TestName',
$VAR3 = 'DummyName1';
$VAR4 = {          'PrimaryKey' => '',
          'ComputeNode' => 'TestName',
          'ip_addr' => '|',
          'vm_uuid' => '|',
          'name' => 'bond0.2004|vhost0|pkt0|',
          'config_name' => '|'        };
$VAR5 = 'DummyName2';
$VAR6 = {          'name' => 'tap98655839-61|',
          'config_name' => 'TestValue',
          'ip_addr' => '107.250.162.244|',
          'vm_uuid' => '903904a7-6b05-489c-9945-ee69cbf5c94f|',
          'ComputeNode' => 'TestName',
          'PrimaryKey' => 'MULTI-SITE: TESTING FOR MULTI-SITE FOR 1607'        };
$VAR7 = 'ZTestName2',
$VAR8 = {          'ComputeNode' => 'TestName',
          'PrimaryKey' => 'ZTestName',
          'config_name' => 'TestValue',
          'name' => 'tap2000b14d-29|tap3ea0942c-66|tap479c2ab0-4e|tapc1c4f00b-de|',
          'ip_addr' => '107.239.45.6|107.250.169.168|107.243.36.9|107.239.44.9|',
          'vm_uuid' => 'ae7aa321-6e3a-4572-a783-ebfcf250ed98|'        };

我正在尝试的代码是

my @keys = keys %Final; 
my @values=values %Final; #value to be inserted - this doesnt work, as its hash ref in my opinion
my $sth=$dbh->prepare("INSERT INTO `$table`(@keys) VALUES (@values)");

这段代码将获取键名和值(这本身就是一个哈希引用)..将上面提到的2D哈希数据插入mysql表的好方法是什么?

1 个答案:

答案 0 :(得分:-1)

尝试使用类似的东西:

foreach my $real_hashref_to_insert ( values %Final ){
    my @keys = keys %$real_hashref_to_insert;
    my @values = values %$real_hashref_to_insert;
    my $field_placeholders = join ", ", map {'?'} @keys;
    my $sth=$dbh->prepare("INSERT INTO `$table`(".join ',' @keys.") VALUES ($field_placeholders)");
    $sth->execute(@{$real_hashref_to_insert}{@keys}); #hash slice
}

DBI recipes post on Perl Monks的启发。