[英]How to use postgres dbd placeholders for DB Object names
(or How to iterate thru information schema Using perl DBI (DBD::PG) and placeholders?) (或如何使用perl DBI(DBD :: PG)和占位符迭代信息架构?)
Windows 7, ActiveState Perl 5.20.2, PostgreSQL 9.4.1 . Windows 7,ActiveState Perl 5.20.2,PostgreSQL 9.4.1。
Cases A, B and C below were successful when using a placeholder for a COLUMN VALUE. 使用占位符作为COLUMN值时,以下情况A,B和C成功。 In order
为了
no placeholder used 没有使用占位符
passed a literal 通过文字
passed a variable (populated with same literal) 传递了一个变量(用相同的文字填充)
It would be great to raise it up a level to DB Objects.. (tables, views etc) 将其提升到数据库对象的级别将是很棒的..(表,视图等)
Here's the output with the error for Case D: 以下是案例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.
Much obliged for any direction! 任何方向都必须承担!
#!/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
I've tried single/double/sans quotes (q, qq)... 我试过单/双/无引号(q,qq)...
If 如果
SELECT * FROM Foo WHERE field = ?
means 手段
SELECT * FROM Foo WHERE field = 'val'
then 然后
SELECT * FROM ?
means 手段
SELECT * FROM 'Table'
and that's obviously wrong. 这显然是错误的。 Placeholders can only be used in an expression.
占位符只能在表达式中使用。 Fix:
固定:
my $sthD = $dbh->prepare("
SELECT COUNT(*)
FROM ".$dbh->quote_identifier($table)."
WHERE status = 'Draft'
");
$sthD->execute();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.