1

我有一个哈希,我正在尝试将其值插入数据库。哈希定义如下:

my %hash = (
            1   =>  'First Word',
            2   =>  'Second Word is correct',
            0   =>  'Third word does not exist',
            );

我不知道如何使用散列在数据库中插入值。我注意到我的问题与这个问题相似。但是,似乎没有一个答案是正确的。在使用任何列出的答案时,不会插入 hash 中的值,而是插入对 hash 的引用,即ARRAY(0x9e63b30)。但是当 I 时print Dumper @values,值会被打印出来,而不是参考值。

关于如何插入值而不是它们的引用的任何建议?并且,问题的答案中列出的解决方案出了什么问题

@values 的定义与此问题相同,即

my @values = values %hash;

编辑:数据库结构:

T1:

sid  sentence
1    First Word
2    Second Word is correct
0    Third word does not exist

在上面的 sid 是keys散列的,句子是values散列的。

这是我尝试过的(这是问题的答案之一

my @keys = keys %hash;

my @values = values %hash;

my $sth = $dbh->prepare("INSERT INTO T1(sid, sentence) VALUES (?,?);");

$sth->execute_array({},\@keys, \@values);

再次,在插入@values参考值的同时被插入。

编辑:

_输出_

$VAR1 = 'First Word';
$VAR2 = 'Third word does not exist';
$VAR3 = 'Second Word is correct';

_ CODE _ 这就是我将值插入 %hash 的方式

my $x=0;
foreach my $file(@files){
        if ($file =~ /regex/){
                push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6 $7"); 
        }
        elsif ($file =~ /regex/){
                push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6");
        }
        elseif ($file =~ /Hs_(.+)_(.+)_(.+)_(.+)_(.+)_W.+txt/){
                push (@{$hash{$x}}, "$1 $2 $3 $4 $5");
        }
$x++;
}
4

3 回答 3

2

That's not what you originally posted!!! You have a hash of reference to arrays. Read the perl reference tutorial (perlreftut) to learn about them.

(Use the command

perldoc perlreftut

to access this tutorial)

于 2009-11-30T23:17:02.590 回答
0

这应该有效。

my $key;
my $value;
while (($key, $value) = each %hash) {
    $sth->bind_param(1, $key);
    $sth->bind_param(2, $value);
    $sth->execute();
}
于 2009-11-30T21:07:15.290 回答
0

更新:

我建议您从上一个线程中获取一个功能示例,并让它在您的计算机上与您的数据库一起工作。一旦您可以使这些示例之一正常工作,那么您应该能够修复自己的代码。


上一个答案:

我在另一个使用的线程上的回复execute_array()也有效,我在发布之前对其进行了测试。

于 2009-11-30T21:19:02.350 回答