【问题标题】:Is there a more concise way to check if PGResult is empty?有没有更简洁的方法来检查 PGResult 是否为空?
【发布时间】:2011-08-08 20:57:46
【问题描述】:

我正在使用 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

【问题讨论】:

  • 作为提示,我强烈建议将Sequel ORM gem 与 Postgres 或 MySQL 或几乎任何其他数据库一起使用。它允许您使用原始 SQL 或数据集,或充当类似于 ActiveRecord 的成熟建模 ORM。
  • 谢谢。但出于性能原因,我想靠近金属。我正在编写开销启动时间最少的东西。我已经尝试过主动记录方法,但启动时间很慢。

标签: ruby postgresql pg


【解决方案1】:

ntuples,打错字了?使用zero? 比使用== 0 更快更简洁

if res.num_tuples.zero?

【讨论】:

  • num_tuples 只是ntuples 的别名。它们都产生相同的结果。好老的猴子补丁(!)
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2022-01-24
相关资源
最近更新 更多