2012-11-25 57 views
3

與perl dbi sqlite有問題。Perl dbi sqlite'select * ..'只返回第一個元素

我建立了一個數據庫(並用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 $_; 
} 

回答

6

fetchrow_array()只提取一行。

嘗試

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

你應該加上'strict'ures到你的答案,以提高它的陣列。否則,你就會發現。 – simbabque

6

根據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"; 
} 
+0

DBI-> connect()的密碼參數中的代碼存在錯誤, – capfan