如何在使用Perl DBI-> MySQL时检查空集

时间:2012-10-12 13:36:30

标签: mysql perl dbi

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

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

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

4 个答案:

答案 0 :(得分:2)

试试:

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

unless ($sth->fetch()) { do something..; }

答案 1 :(得分:2)

  

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

$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
unless( $sth->rows ) {
    #empty set
}

答案 2 :(得分:2)

我建议您初步获取记录数量,例如

my ($records) = $dbh->selectrow_array('SELECT count(*) FROM table_name_here');

答案 3 :(得分: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) { ... }