如何使用postgres dbd占位符作为DB对象名称

时间:2015-05-13 00:09:19

标签: perl postgresql

(或如何使用perl DBI(DBD :: PG)和占位符迭代信息模式?)

Windows 7,ActiveState Perl 5.20.2,PostgreSQL 9.4.1。

使用占位符作为COLUMN VALUE时,下面的案例A,B和C成功。

  • 没有使用占位符

  • 传递了一个文字

  • 传递了一个变量(填充了相同的文字)

将它提升到数据库对象......(表,视图等)

是很棒的

这里是案例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)......

1 个答案:

答案 0 :(得分: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();