有没有办法检查 DBI->execute 语句是否返回一个空集?目的是我想创建一个表,然后询问用户名,如果用户名不在表中,(检查空的 fetch() 语句),然后添加到表中。有什么建议么?
$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
if(...$sth->fetch() was empty...)
do something...
试试看:
$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
unless ($sth->fetch()) { do something..; }
我建议你初步获取记录数,像这样
my ($records) = $dbh->selectrow_array('SELECT count(*) FROM table_name_here');
有没有办法检查 DBI->execute 语句是否返回空集
是的。
$sth = $dbh->prepare("SELECT * FROM table_name_here");
$sth->execute();
unless( $sth->rows ) {
#empty set
}
一种可能的方法是:
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) { ... }