2016-02-05 28 views
0

我有一個perlDBImysql查詢,看起來像這樣:Perl的DBI哪裏是空與未定義的變量

my $rows = get_rows(
    "select id from table where column1=?, column2=? and column3=?", 
    $var1,$var2,$var3 
    ); 

sub get_rows { 

    my $sql = shift; 
    my @vars = @_;  
    my $sth = $dbh->prepare($sql); 
    $sth->execute(@vars); 
    my $rows = $sth->fetchall_arrayref(); 
    $sth->finish();   
    return $rows; 
    } 

我跑這來檢查,如果一個特定的行存在包含這些增值經銷商。但是我遇到的問題是處理NULL值。這些必須被選擇爲IS NULL而不是=?,這往往會丟失包含NULL值的行。例如,如果變量1,2和3包含'12','23'undeftable包含12,23NULL,則查詢將不返回任何結果。有沒有簡單的方法來將012f的undef值轉換爲IS NULL值?

+2

您的整個'get_rows'函數可以被DBI的'selectall_hashref'方法取代。 – simbabque

+2

@simbabque,你的意思是'selectall_arrayref'。 – cjm

+0

@cjm當然是。 – simbabque

回答

2

這記錄在DBINULL值

$sql_clause = defined $age? "age = ?" : "age IS NULL"; 
$sth = $dbh->prepare(qq{ 
    SELECT fullname FROM people WHERE $sql_clause 
}); 
$sth->execute(defined $age ? $age :()); 
+0

謝謝。沒有看到這個。我最終修改了查詢而不是代碼,就像DBI文檔中的建議之一一樣。 – D2J2