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

Mar*_*ark 1 postgresql perl

(或如何使用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.
Run Code Online (Sandbox Code Playgroud)

任何方向都有很大的帮助!

#!/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
Run Code Online (Sandbox Code Playgroud)

我试过单/双/无引号(q,qq)......

ike*_*ami 5

如果

SELECT * FROM Foo WHERE field = ?
Run Code Online (Sandbox Code Playgroud)

手段

SELECT * FROM Foo WHERE field = 'val'
Run Code Online (Sandbox Code Playgroud)

然后

SELECT * FROM ?
Run Code Online (Sandbox Code Playgroud)

手段

SELECT * FROM 'Table'
Run Code Online (Sandbox Code Playgroud)

这显然是错的.占位符只能在表达式中使用.固定:

my $sthD = $dbh->prepare("
   SELECT COUNT(*)
    FROM ".$dbh->quote_identifier($table)."
   WHERE status = 'Draft'
");
$sthD->execute();
Run Code Online (Sandbox Code Playgroud)