2014-11-24 59 views
0

我运行:使用未初始化值的fetchrow后()

my $config = ""; 
my $dsn = "dbi:SQLite:dbname=test.db"; 
my $dbh = DBI->connect(   
    $dsn, 
    "", 
    "", 
    { RaiseError => 1} 
) or die $DBI::errstr; 

my $sth = $dbh->prepare("SELECT config FROM tests WHERE status=1"); 
$sth->execute();  
my $config = $sth->fetchrow(); 
if($config ne "") 
{ 
    print "found!" 
} 
$sth->finish(); 
$dbh->disconnect(); 

为什么我越来越

Use of uninitialized value $config in string ne at ..... 
+0

打开;'和'使用警告;'。可能'fetchrow'正在返回undef。为什么你测试它是一个空字符串呢? – Sobrique 2014-11-24 17:41:04

+0

我加入'use strict;使用警告;使用DBI;'到我的代码 – 2014-11-24 17:42:04

+1

数据库中的'config'为空吗? – AKHolland 2014-11-24 17:42:13

回答

3

没有记载fetchrow。您应该使用fetchrow_array

问题是,DBI返回值undef设置为NULL在数据库中的值。所以my $config = $sth->fetchrow_array$configundef要么是否有表,如果发现该行有一个configNULL值找不到匹配的行。这意味着它不能用于测试表中是否有任何匹配的行。此外,你不能比较的undef价值,如果它是一个字符串 - 它会引发错误你看到

Use of uninitialized value $config in string ne 

,所以你需要测试fetchrow_array是否返回一个空列表,或者如果fetchrow_arrayref返回一个未定义的值。

您的代码应该是`使用严格的两种

my @config = $sth->fetchrow_array; 
if (@config) { 
    print "found!" 
} 

my $config = $sth->fetchrow_arrayref; 
if (defined $config) { 
    print "found!" 
} 
+0

这不起作用。双方再次给了我同样的错误 – 2014-11-24 17:49:11

+1

这不可能是真的:第一个例子没有'$ config' – Borodin 2014-11-24 17:50:42

+1

'作为'fetchrow_array'别名fetchrow'工作正常。在启用警告的情况下针对字符串检查未定义的值是他的问题。 – AKHolland 2014-11-24 17:50:42