有没有更简洁的方法来检查PGResult是否为空?

时间:2011-04-19 17:14:56

标签: ruby postgresql pg

我正在使用pg gem与Ruby的PostgreSQL交谈。有没有 比使用res.ntuples == 0更好的方法来检查是否没有结果?

conn = PGconn.connect config

cmd = "select * from labels inner join labels_mail using(label_id) " + 
  "where labels_mail.mail_id = $1 and labels.name = $2"

res = conn.exec(cmd, [mail_id, mailbox])

if res.ntuples == 0  #  <=== is there a better way to check this?
  cmd = "insert into labels_mail (mail_id, label_id) values ($1, $2)"
  conn.exec(cmd, [mail_id, label_id(mailbox)])
end

1 个答案:

答案 0 :(得分:5)

ntuples,这是一个错字?使用zero?== 0

更快更简洁
if res.num_tuples.zero?