1

有没有办法检查 DBI->execute 语句是否返回一个空集?目的是我想创建一个表,然后询问用户名,如果用户名不在表中,(检查空的 fetch() 语句),然后添加到表中。有什么建议么?

    $sth = $dbh->prepare("SELECT * FROM table_name_here");
    $sth->execute();

    if(...$sth->fetch() was empty...)
    do something...
4

4 回答 4

2

试试看:

$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();

unless ($sth->fetch()) { do something..; }
于 2012-10-12T13:38:53.497 回答
2

我建议你初步获取记录数,像这样

my ($records) = $dbh->selectrow_array('SELECT count(*) FROM table_name_here');
于 2012-10-12T15:37:16.880 回答
2

有没有办法检查 DBI->execute 语句是否返回空集

是的。

$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
unless( $sth->rows ) {
    #empty set
}
于 2012-10-12T14:30:49.097 回答
1

一种可能的方法是:

my $row_count = 0;
while (my @ary = $sth->fetchrow_array() ) { ...; $row_count++; }
unless ($row_count) { 
  ...
}

但我不禁想知道为什么你需要使用fetchrow,而不是fetchall,对于这种特定情况。事实上,我会这样重组它:

my ($count) = $dbh->selectrow_array('
   SELECT COUNT(*) FROM users WHERE username = ?'
   undef, $username);
if ($count) { ... } 
于 2012-10-12T13:41:26.007 回答