2009-11-25 45 views
1

我需要將哈希值插入到數據庫中。以下是代碼模板我要插入table1中列關鍵值:如何使用Perl的DBI模塊將哈希值插入到數據庫中?

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; 

我知道如何插入使用數組即使用execute_array()值,但不知道如何插入當前值%hash在table1中。

有什麼建議嗎?

+1

究竟做'%散列「包含? – 2009-11-25 18:11:11

+0

那有什麼關係?它正好定義了散列應該被定義的方式。 – shubster 2009-11-25 18:27:07

+1

散列的結構是問題的重要部分。你已經有了兩個不同的答案,從不同的角度理解問題的人,因爲不清楚哈希裏面是什麼。 – 2009-11-25 19:50:13

回答

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數據庫的工作,否則我會使用它作爲一個例子。)

0

也許你可以嘗試使用

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

這是你想達到什麼樣的?

如果我理解manual正確(「每個參數元組(值的組)執行準備語句一旦[...]通過傳遞...基準」)它也應該可以簡單地以

($tuples, $rows) = $sth->execute_array(\%hash) or die $sth->errstr; 
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

+1

我用這種方法看到的問題是,可能會遇到不正確地轉義參數的陷阱。我總是推薦使用佔位符!除此之外,好主意。 – Simon 2009-11-25 19:59:16

+0

啊,謝謝你指出。我只是更新了上面的代碼來解決這個問題。對不起,錯過了。 – 2009-11-25 21:17:20

+0

對不起,如果這是一個愚蠢的問題,但Custom :: Module :: Make ::應該根據你的DBH的位置改變嗎? – ado 2013-05-29 05:07:20

1

嘗試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; 
相關問題