2013-10-28 32 views
2

我在Informix表中有記錄。該表列如下所示:如何在Perl的DBI中正確表示空格

acct_no integer, 
suffix char(1), 
meter_num char(20), 
date_read datetime year to second not null , 
counter smallint, 
reading integer not null , 
typeofread char(1), 
estimated char(1), 
time_billed datetime year to second 

使用Informix的DBACCESS工具:

select * 
from ws_mtrread 
where acct_no = 113091000 
and suffix = " " 
order by date_read desc; 

這個結果(最新的顯示)返回和我的作品無論是否使用一個或兩個空格的後綴。

acct_no  113091000 
suffix 
meter_num 34153205 
date_read 2013-09-09 23:31:15 
counter  0 
reading  1240 
typeofread g 
estimated 
time_billed 2013-10-22 11:48:21 

然而,這Perl的DBI查詢

my $sql_statement = 
"select * ". 
"from ws_mtrread ". 
"where acct_no = ? ". 
"and suffix = ? ". 
"order by date_read desc ; "; 

不起作用。我可以在不指定$ suffix的情況下獲取行,所以我知道該行存在。

我相信這是我代表後綴的錯誤。在這個例子中,後綴等於一個由兩個空格組成的字符串。

如何正確表示空格,以便查詢有效?以下是我用於獲取該行的其餘代碼。

my $test_acct_no = 113091000; 
my $suffix = " "; 

my $pt_sel_hdl = $DBHdl->prepare($sql_statement); 

$pt_sel_hdl->execute($test_acct_no, $DBHdl->quote($suffix)); 

my $ws_mtr_read_rec_ref = $pt_sel_hdl->fetchrow_hashref; 

調用之後,$ ws_mtr_read_rec_ref未定義。

+0

我會嘗試,但這是一個問題。 Informix接受分號來終止一個字符串。爲什麼會這樣呢? – octopusgrabbus

+0

@Barmar這是Informix,而不是MySQL。 – octopusgrabbus

+0

我不知道如何表示errstr()。如果我按照你列出的方式使用它,它會變得不確定。 – octopusgrabbus

回答

4

不要使用DBI的quote方法在這裏:

$pt_sel_hdl->execute($test_acct_no, $DBHdl->quote($suffix)); 

當您在SQL中使用?佔位符,數據庫驅動程序將正確參數,你傳遞給execute查詢參數。 (只有兩個空格)您可能正在創建查詢時要搜索被搜索的文字字符串" "(包括引號)

因此,這應該是所有您需要:

$pt_sel_hdl->execute($test_acct_no, $suffix); 
+0

謝謝。這非常有幫助。 – octopusgrabbus

+0

沒錯。 quote()適用於不使用佔位符時,並且希望將您的參數直接插入帶有括號引號的SQL語句中。 – runrig

+0

@runrig我正在慢慢改變我所有的$ sql_statement變量來使用佔位符。 Informix 4GL與嵌入式值或佔位符一起工作,所以我習慣了兩種方法。我通常使用準備好的語句和4GL中的佔位符。 – octopusgrabbus