【问题标题】:Perl dbi sqlite 'select * ..' only returns first elemPerl dbi sqlite 'select * ..' 只返回第一个元素
【发布时间】:2012-11-13 08:07:00
【问题描述】:

perl dbi sqlite 有问题。

我已经建立了一个数据库(并用 sqlite 命令行检查了它)。 现在我想在这个数据库中搜索,它没有用。

所以我试着做一个'SELECT *' 这只打印数据库中的第一个元素,而不是该表中的所有内容。

我认为导致 select * 失败的错误与阻止我使用“like %..%”内容的错误相同。

这是相关代码,如果代码正确且数据库表看起来不错,还有什么可能导致问题?

 my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") || die "Cannot connect: $DBI::errstr";

my $sth = $dbh->prepare('SELECT * FROM words');
$sth->execute;
my @result = $sth->fetchrow_array();


foreach( @result) {
    print $_;
}

【问题讨论】:

    标签: perl sqlite select dbi


    【解决方案1】:

    fetchrow_array() 只获取一行。

    试试

    while ( my @row = $sth->fetchrow_array ) {
      print "@row\n";
    }
    

    【讨论】:

    • 您应该将strictures 添加到您的答案中以改进它。否则,你就当场了。
    【解决方案2】:

    根据the documentationfetchrow_array

    获取下一行数据并将其作为包含字段值的列表返回。

    如果你想要所有的数据,你可以重复调用fetchrow_array(或fetchrow_arrayref)直到你到达表格的末尾,或者你可以使用fetchall_arrayref

    fetchall_arrayref 方法可用于从准备和执行的语句句柄中获取要返回的所有数据。它返回对数组的引用,其中每行包含一个引用

    代码如下所示

    use strict;
    use warnings;
    
    use DBI;
    
    my $dbfile = 'words.db';
    
    my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile", '', '') or die "Cannot connect: $DBI::errstr";
    
    my $sth = $dbh->prepare('SELECT * FROM words');
    $sth->execute;
    my $result = $sth->fetchall_arrayref;
    
    foreach my $row ( @$result ) {
      print "@$row\n";
    }
    

    【讨论】:

    • DBI->connect()的密码参数处的代码有错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2014-02-26
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多