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を使用する方法は知っていますが、table1execute_array()にある値を挿入する方法がわかりません。%hash

助言がありますか?

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

これはあなたが達成しようとしていることですか?

マニュアルを正しく理解していれば(「渡された参照を介して、パラメータータプル(値のグループ)[...]ごとにプリペアドステートメントを1回実行する...」)、次のことも簡単に実行できるはずです。

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