1

我需要将哈希值插入数据库。以下是我必须在 table1 列中插入值的代码模板:

use DBI;
use strict;

%hash; #assuming it already contains desired values
my $dbh = DBI->connect(
      "dbi:Sybase:server=$Srv;database=$Db", 
      "$user", "$passwd"
) or die sprintf 'could not connect to database %s', DBI->errstr;
my $query= "Insert INTO table1(key, values) VALUES (?,?) ";
my $sth = $dbh->prepare($query) 
    or die "could not prepare statement\n", $dbh->errstr;
$sth-> execute or die "could not execute", $sth->errstr; 

我知道如何使用数组即 use 插入值execute_array(),但不知道如何插入%hashtable1 中存在的值。

有什么建议么?

4

4 回答 4

6

以下使用execute_array您问题中提到的功能。我测试了它。

my $dbh = DBI->connect("DBI:mysql:database=$DB;host=$host;port=$port", $user, $password);

my %hash = (
            1   =>  'A',
            2   =>  'B',
            0   =>  'C',
            );

my @keys = keys %hash;

my @values = values %hash;

my $sth = $dbh->prepare("INSERT INTO table1(id, value) VALUES (?,?);");

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

(抱歉,我没有可使用的 Sybase 数据库,或者我会使用它作为示例。)

于 2009-11-25T20:15:50.833 回答
2

试试SQL::Abstract

use DBI;
use SQL::Abstract;
use strict;

%hash; #assuming it already contains desired values
my $dbh = DBI->connect(
      "dbi:Sybase:server=$Srv;database=$Db", 
      "$user", "$passwd"
) or die sprintf 'could not connect to database %s', DBI->errstr;

my ($query, @bind) = $sql->insert("tableName", \%hash);
my $sth = $dbh->prepare($query) 
    or die "could not prepare statement\n", $dbh->errstr;
$sth-> execute (@bind) or die "could not execute", $sth->errstr;
于 2014-12-10T07:04:57.643 回答
1

这是构建查询的最简单的方法。我通常会做这样的事情,因为我还没有找到另一种解决方法。

use strict;
use DBI;

my $dbh = Custom::Module::Make::DBH->connect('$db');

my %hash = (
    apple  => 'red',
    grape  => 'purple',
    banana => 'yellow',
);

my $keystr = (join ",\n        ", (keys %hash));
my $valstr = join ', ', (split(/ /, "? " x (scalar(values %hash))));
my @values = values %hash;

my $query = qq`
    INSERT INTO table1 (
        $keystr
    )
    VALUES (
        $valstr
    )
`;

my $sth = $dbh->prepare($query) 
    or die "Can't prepare insert: ".$dbh->errstr()."\n";

$sth->execute(@values)
    or die "Can't execute insert: ".$dbh->errstr()."\n";

但有可能我也没有正确理解这个问题:P

于 2009-11-25T19:42:35.530 回答
0

也许你可以尝试使用

for my $key (keys %hash) {
  $sth->execute($key, $hash{$key}) or die $sth->errstr;
}

这是你想要达到的目标吗?

如果我正确理解了手册(“为每个参数元组(值组)执行一次准备好的语句[...]通过引用传递...”)也应该可以简单地

($tuples, $rows) = $sth->execute_array(\%hash) or die $sth->errstr;
于 2009-11-25T18:09:53.957 回答