2015-05-13 26 views
1

(或如何迭代通信息模式使用perl DBI(DBD :: PG)和佔位符?)如何使用Postgres的DBD佔位符數據庫對象名稱

Windows 7中的ActiveState Perl的5.20.2和PostgreSQL 9.4。 1。

以下情況A,B和C在使用COLUMN VALUE的佔位符時成功。爲了

  • 沒有佔位符使用

  • 通過文字

  • 傳遞一個變量(填入相同的文字)

這將是巨大的,以提高它了級別到DB對象..(表格,視圖等)

這裏對於情況D的錯誤輸出:

Z:\CTAM\data_threat_mapping\DB Stats\perl scripts>test_placeholder.pl 

A Row Count: 1 
B Row Count: 1 
C Row Count: 1 

DBD::Pg::st execute failed: ERROR: syntax error at or near "$1" 

LINE 1: SELECT COUNT(*) FROM $1 WHERE status = 'Draft'; 
          ^at Z:\CTAM\data_threat_mapping\DB  Stats\perl 
scripts\test_placeholder.pl line 34. 

對任何方向都非常感興趣!

#!/usr/bin/perl -w 
use strict; 
use diagnostics; 
use DBI; 

my $num_rows = 0; 

# connect 
my $dbh = DBI->connect("DBI:Pg:dbname=CTAM;host=localhost", 
         "postgres", "xxxxx", 
         { 'RaiseError' => 1, pg_server_prepare => 1 }); 

#--------------------- 
# A - success 
my $sthA = $dbh->prepare(
    "SELECT COUNT(*) FROM cwe_compound_element WHERE status = 'Draft';" 
); 
$sthA->execute(); # no placeholders 

#--------------------- 
# B - success 
my $sthB = $dbh->prepare (
    "SELECT COUNT(*) FROM cwe_compound_element WHERE status = ?;" 
); 
$sthB->execute('Draft'); # pass 'Draft' to placeholder 

#--------------------- 
# C - success 
my $status_value = 'Draft'; 
my $sthC = $dbh->prepare(
    "SELECT COUNT(*) FROM cwe_compound_element WHERE status = ?;" 
); 
$sthC->execute($status_value); # pass variable (column value) to placeholder 

#--------------------- 
# D - failure 
my $sthD = $dbh->prepare(
    "SELECT COUNT(*) FROM ? WHERE status = 'Draft';" 
); 
$sthD->execute('cwe_compound_element'); # pass tablename to placeholder 

我試過單/雙/沒有引號(Q,QQ)......

回答

5

如果

SELECT * FROM Foo WHERE field = ? 

意味着

SELECT * FROM Foo WHERE field = 'val' 

然後

SELECT * FROM ? 

意味着

SELECT * FROM 'Table' 

這顯然是錯誤的。佔位符只能用於表達式中。修復:

my $sthD = $dbh->prepare(" 
    SELECT COUNT(*) 
    FROM ".$dbh->quote_identifier($table)." 
    WHERE status = 'Draft' 
"); 
$sthD->execute(); 
相關問題